An array is a data structure used to store a collection of values that all have the same data type.
Array Declaration and Allocation
To declare an array, you start as you would a normal variable declaration, but in addition, you append a set of square brackets following the array’s name. The brackets contain the number of elements in the array. The default values for these elements are the same as for variables—elements in global arrays are initialized to their default values, and elements in local arrays remain uninitialized.
int myArray[3]; /* integer array with 3 elements */
Array Assignment
To assign values to the elements, you can reference them one at a time by placing the element’s index inside the square brackets, starting with zero.
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
Alternatively, you can assign values at the same time as the array is declared by enclosing them in curly brackets. The specified array length may optionally be left out to let the array size be decided by the number of values assigned.
int myArray[3] = { 1, 2, 3 };
int myArray[] = { 1, 2, 3 }; /* alternative */
Once the array elements are initialized, they can be accessed by referencing the index of the element you want.
printf("%d", myArray[0]); /* 1 */
Multi-Dimensional Arrays
Arrays can be made multi-dimensional by adding more sets of square brackets. As with single-dimensional arrays, they can either be filled in one at a time or all at once during the declaration.
int mArray[2][2] = { { 0, 1 }, { 2, 3 } };
mArray[0][0] = 0;
mArray[0][1] = 1;
The extra curly brackets are optional, but including them is good practice since it makes the code easier to understand.
int mArray[2][2] = { 0, 1, 2, 3 }; /* alternative */
Arrays and Pointers
An array in C can be treated as a constant pointer that points to the first element in the array. As such, array elements can referenced just as well with pointer arithmetic. By incrementing the pointer by one, you move to the next element in the array, because changes to a pointer’s address are implicitly multiplied by the size of the pointer’s data type.
*(myArray+1) = 10; /* myArray[1] = 10; */
Pointer arithmetic is an advanced feature that should be used with care. The four arithmetic operators that can be used with pointers include: +, -, ++, and --.
int* ptr = &myArray;
printf("Address of myArray[0]: %p \n", ptr); /* ex. 0028FF14 */
ptr++;
printf("Address of myArray[1]: %p", ptr); /* ex. 0028FF18 */
Array Size
Just as with any other pointer it is possible to exceed the valid range of an array and thereby rewrite some adjacent memory. This should always be avoided since it can lead to unexpected results or crash the program.
int myArray[2] = { 1, 2 };
myArray[2] = 3; /* out of bounds */
To determine the length of a regular (statically allocated) array, the sizeof operator
can be used.
int length = sizeof(myArray) / sizeof(int); /* 2 */