It is possible to initialize an array at declaration time. The general initialization form for one-dimensional arrays is:
where the number of elements inside the {} is equivalent to the value of "some constant expression". If not enough initialization values are included, the remaining array elements are initialized to 0. When initializing an array in this form, it is legal to leave out "some constant expression" inside the square brackets since the compiler can determine the size of the array from the number of initialization values.
One can initialize a multi-dimensional array in the same way - by including a list of initialization values. To make it easier to keep track of which value goes into which array element, it is possible to group initialization values by dimension. For example,
Note that the column dimension (second or [2]) varies the fastest.
The following example declares and initializes x as a one-dimensional array that has three members, because no size was specified and there are three initializers:
int x[] = { 1, 3, 5 };
The next example shows a completely bracketed initialization: 1, 3, and 5 initialize the first row of the array y[0], namely y[0][0], y[0][1], and y[0][2]. Likewise, the next two lines initialize y[1] and y[2]. The initializer ends early, and therefore y[3] is initialized with 0:
float y[4][3] =
{
{ 1, 3, 5 },
{ 2, 4, 6 },
{ 3, 5, 7 },
};
The next example achieves precisely the same effect. The initializer for y begins with a left brace but that for y[0] does not; therefore, three elements from the list are used. Likewise, the next three are taken successively for y[1] and y[2]:
float y[4][3] =
{
1, 3, 5, 2, 4, 6, 3, 5, 7
};
The next example initializes the first column of y (regarded as a two-dimensional array) and leaves the rest 0:
float y[4][3] = {
{ 1 }, { 2 }, { 3 }, { 4 }
};
Items of Note
Multi-dimensional array elements are accessed the same way as singly dimensioned arrays, using as many indices as there are dimensions. Thus, to input a value into the "3rd row, 5th column" of the 'pricesByYear' table defined above, we would write:
(Remember, since array indices start counting from 0, the indices in this code are one less than the values used in the verbal description.)
Since the individual elements represent some specific type, one can use array elements of some type anywhere that one can use non-array elements of that same type. However, with few exceptions, one cannot perform an operation on an array as a whole. It is therefore illegal, for example, to write: