C Language Declaring and initializing an array


Example

The general syntax for declaring a one-dimensional array is

type arrName[size];

where type could be any built-in type or user-defined types such as structures, arrName is a user-defined identifier, and size is an integer constant.

Declaring an array (an array of 10 int variables in this case) is done like this:

int array[10];

it now holds indeterminate values. To ensure it holds zero values while declaring, you can do this:

int array[10] = {0};

Arrays can also have initializers, this example declares an array of 10 int's, where the first 3 int's will contain the values 1, 2, 3, all other values will be zero:

int array[10] = {1, 2, 3};

In the above method of initialization, the first value in the list will be assigned to the first member of the array, the second value will be assigned to the second member of the array and so on. If the list size is smaller than the array size, then as in the above example, the remaining members of the array will be initialized to zeros. With designated list initialization (ISO C99), explicit initialization of the array members is possible. For example,

int array[5] = {[2] = 5, [1] = 2, [4] = 9}; /* array is {0, 2, 5, 0, 9} */

In most cases, the compiler can deduce the length of the array for you, this can be achieved by leaving the square brackets empty:

int array[] = {1, 2, 3}; /* an array of 3 int's */
int array[] = {[3] = 8, [0] = 9}; /* size is 4 */

Declaring an array of zero length is not allowed.

C99C11

Variable Length Arrays (VLA for short) were added in C99, and made optional in C11. They are equal to normal arrays, with one, important, difference: The length doesn't have to be known at compile time. VLA's have automatic storage duration. Only pointers to VLA's can have static storage duration.

size_t m = calc_length(); /* calculate array length at runtime */
int vla[m];               /* create array with calculated length */

Important:

VLA's are potentially dangerous. If the array vla in the example above requires more space on the stack than available, the stack will overflow. Usage of VLA's is therefore often discouraged in style guides and by books and exercises.