Variable-Length Arrays 115
Pay particular attention to the syntax of the preceding statement. Note that commas are
required after each brace that closes off a row, except in the case of the final row.The use
of the inner pairs of braces is actually optional. If not supplied, initialization proceeds by
row. Thus, the preceding statement could also have been written as follows:
int M[4][5] = { 10, 5, -3, 17, 82, 9, 0, 0, 8, -7, 32,
20, 1, 0, 14, 0, 0, 8, 7, 6 };
As with one-dimensional arrays, it is not required that the entire array be initialized. A
statement such as
int M[4][5] = {
{ 10, 5, -3 },
{ 9, 0, 0 },
{ 32, 20, 1 },
{ 0, 0, 8 }
};
only initializes the first three elements of each row of the matrix to the indicated values.
The remaining values are set to 0. Note that, in this case, the inner pairs of braces are
requiredto force the correct initialization.Without them, the first two rows and the first
two elements of the 3rd row would have been initialized instead. (Verify to yourself that
this is the case.)
Subscripts can also be used in the initialization list, in a like manner to single-
dimensional arrays. So the declaration
int matrix[4][3] = { [0][0] = 1, [1][1] = 5, [2][2] = 9 };
initializes the three indicated elements of matrixto the specified values.The unspecified
elements are set to zero by default.
Va r iable-Length Arrays
1
This section discusses a feature in the language that enables you to work with arrays in
your programs without having to give them a constant size.
In the examples in this chapter, you have seen how the size of an array is declared to
be of a specific size.The C language allows you to declare arrays of a variable size. For
example, Program 7.3 only calculates the first 15 Fibonacci numbers. But what if you
want to calculate 100 or even 500 Fibonacci numbers? Or, what if you want to have the
user specify the number of Fibonacci numbers to generate? Study Program 7.8 to see
one method for resolving this problem.
- As of this writing, full support for variable-length arrays was not offered by all compilers.You
might want to check your compiler’s documentation before you use this feature.