Reader small image

You're reading from  Learn C Programming. - Second Edition

Product typeBook
Published inAug 2022
PublisherPackt
ISBN-139781801078450
Edition2nd Edition
Right arrow
Author (1)
Jeff Szuhay
Jeff Szuhay
author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay

Right arrow

Chapter 11: Working with Arrays

We have already seen how a structure is a grouping of one or more components that can each be of different data types. Often, we need a grouping that consists of the same type; this is called an array. An array is a collection of multiple occurrences of the same data type grouped together under a single name. Each element of the array is accessed via its base name and an offset of that base. Arrays have many uses, from organizing homogenous data types to providing the basis for strings, or arrays of characters.

Before we can learn about some of the wide uses of arrays, we need to explore the basics of declaring and manipulating arrays.

The following topics will be covered in this chapter:

  • Declaring an array of values
  • Initializing an array in several ways
  • Understanding variable-length arrays
  • Accessing each element of an array
  • Understanding zero-based array indexing
  • Assigning and manipulating elements of an array
  • ...

Technical requirements

Continue to use the tools chosen from the Technical requirements section of Chapter 1, Running Hello, World!.

The source code for this chapter can be found at https://github.com/PacktPublishing/Learn-C-Programming-Second-Edition/tree/main/Chapter11.

Declaring and initializing arrays

An array is a collection of two or more values, all of which have the same type and share a single common base name. It makes no sense to have an array of just one value; that would simply be a variable. An array definition has the following syntax: dataType arrayIdentifier[ numberOfElements ]; Here, dataType is any intrinsic or custom type, arrayIdentifier is the base name of the array, and numberOfElements specifies how many values of dataType are in the array. numberOfElements, for whatever type and values are given, is a literal constant or expression that will be converted to an integer. Most commonly, numberOfElements is an integer constant expression. An array whose size is defined by a constant expression we call a constant-length array. All the elements of the array are contiguous (or side by side) so that the size of the array is the size of each element multiplied by the number of elements in the array. Once an array is declared, its size...

Understanding variable-length arrays

A Variable-Length Array (VLA) is an array whose size is not known until runtime. The first set of arrays declared earlier have fixed length declarations. The second set of arrays are VLA declarations. A VLA declaration is like a fixed-length declaration, except that the array size is specified by a non-constant expression. Here, non-constant refers to a non-literal variable value.

Remember that a const type is a variable whose value is determined at runtime, so even though it cannot be changed once initialized, it is still considered a variable and not a literal constant. When a VLA declaration is encountered, the size expression is evaluated and the array is created with the resultant length. This length must be a positive integer. Once created, the size of a VLA is fixed and cannot change, just as with constant-length arrays.

So, note that the variable in a VLA means that the array size is defined by some variable value and not that the...

Accessing array elements

Each element of an array is accessed via its base name and an index into the array. An index is also known as a subscript. Each element is accessed using the following form:

arrayName[ index ]

Here, index is a value between 0 and the (array size minus 1). We can access any element of an array using this form. Just as with defining an array, the index may be a literal value, a variable, the result of a function call, or the result of an expression, as follows:

float anArray[10] = {2.0};
int   counter = 9;
float aFloat  = 0.0; 
aFloat = anArray[ 9 ];             // Access last element.
aFloat = anArray[ counter ];       // Access last element 
                             ...

Operating on arrays with loops

When an array is present, a common operation is to iterate over all of its elements. For this, we typically use the for()… loop. We could also use any of the other looping statements described in Chapter 7, Exploring Loops and Iterations. However, because, more often than not, we know the loop's size, it is easier and more reliable to use a counter-controlled for()… loop. When we explore arrays of characters (or strings) in Chapter 15, Working with Strings, we will begin our exploration of sentinel-controlled loops.

To iterate over the array, the index counter is initialized to 0 (to match the zeroth offset), the continuation expression specifies that the index counter remains fewer than the number of elements, and the index counter is incremented at each iteration. The loop is as follows:

const int kArraySize = 25;
int anArray[ kArraySize ];
for( int i=0 ; i < kArraySize ; i++ )  {   
// i...

Using functions that operate on arrays

An array is a collection of variables bound together by a common base name and an offset from that base. In nearly every respect, we can treat an individual element of an array just as we would any other variable. Even with function parameters, array elements can be passed into them as with regular variables, as follows:

#include <math.h>
int anArray[10] = {0};
anArray[3] = 5;
anArray[3] = pow( anArray[3] , 2 );

The fourth element of the array is assigned a value of 5. The function declared in math.h, pow(), is called with the value found in the fourth element of the array and is raised to the power of 2 (squared) and assigned back to the fourth element of the array, which now has a value of 25.

We could write a function that operations on anArray, as follows:

int find10Min( int anArray[10] );

This function prototype specifies that the function definition will only take arrays of size 10 and no other. This is perfectly...

Summary

In this chapter, we learned how arrays are homogenous groupings of data types, unlike structures. We then learned how to declare arrays, as well as how to initialize them in various ways, depending on how they were declared. We learned the differences between constant-length arrays and VLAs for initialization and how they are identical in every other way. We saw that we don't always have to specify the size of an array if we initialize it with values when it is declared. Once an array has been declared, its size is fixed and cannot change. We learned how to access array elements via the element's offset, also known as the index or subscript. We further saw how to manipulate the simplest kind of array – a one-dimensional array – directly via the for()… loop, as well as by using arrays as function parameters.

This chapter is a prerequisite to Chapter 12, Working with Multi-Dimensional Arrays, through to Chapter 16, Creating and Using More Complex...

Questions

  1. What are the three components of an array definition?
  2. What is a constant-length array definition?
  3. What is a variable-length array definition?
  4. Can you initialize a constant-length array when it is defined? Can you initialize a VLA when it is defined?
  5. Why are VLAs useful as function parameters?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn C Programming. - Second Edition
Published in: Aug 2022Publisher: PacktISBN-13: 9781801078450
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay