C - Array Array Initialization


To assign initial values for your array, specify the list of initial values between braces and separate them by commas in the declaration.

For example:

double values[5] = { 1.5, 2.5, 3.5, 4.5, 5.5 };

This declares the values array with five elements.

The elements are initialized with values[0] having the value 1.5, value[1] having the initial value 2.5, and so on.

To initialize the whole array, there must be one value for each element.

If there are fewer initializing values than elements, the elements without initializing values will be set to 0. Thus, if you write:

double values[5] = { 1.5, 2.5, 3.5 };

The first three elements will be initialized with the values between braces, and the last two elements will be initialized with 0.

To initialize an entire array to zero.

double values[5] = {0.0};

If you put more initializing values than array elements, you'll get an error message from the compiler.

You can omit the size of the array for initial values.

The compiler will assume that the number of elements is the number of values in the list:

int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

The size of the array is determined by the number of initial values in the list.

Related Topics