2.12. Arrays¶
- An array is a sequence of data items that are of the same type and stored contiguously in memory.
- Arrays can be one dimensional (single sequence of data), two, three, or N dimensional. Regardless of how the data is indexed (to fit the needs of the program design) it is all stored sequentially.
- The index of the array always goes from 0 to N - 1, where the size of the array is N.
- Square brackets, [size], are used to initialize an array. The size of the array is an integer constant, either a number or a #define constant.
- A variable or expression may be used as an array index when referencing an array, but not when declaring it.
- Automatic (on the stack) arrays are not initialized by default. It is best to never assume an initial value of an array.
- To initialize an array, put the values in brackets.
int a[3] = {3,4,5};
int a[] = {3,4,5}; /* size determined by the initial brackets */
int b[][3] = {{7,8,9},{4,5,6},{3,4,5}}; /* a 3x3 array */
2.12.1. An Array Example¶
#include <stdio.h>
#define N 5
int main(void)
{
int a[N], i, sum=0;
for( i=0; i < N; i++ ) {
a[i] = 7 * i * i;
sum += a[i];
printf( "a[%d] = %d\t", i, a[i] );
}
return 0;
}