
As the last two declarations (variables "e" and "f") illustrates, the last dimension has an unspecified length. In
this case, the length of the sub-array is detected by the associated initialiser. Each sub-array is a different
length. In this specific example, "e[1][5]" includes the letter "l" of the word "Cancel". However, "e[0][5]" is
invalid as the sub-array e[0] only comprises three entries (the letters "O", "K" and the zero terminator). The
difference between the declarations of the "e" and "f" arrays is that we enable the compiler to determine the
number of higher dimensions for "f". "sizeof f" and "sizeof e" are both 2 (see "Arrays and the "sizeof" operator"
on page 168).
12.5.4.5 Arrays and the "sizeof" operator
The "sizeof" operator returns the number of elements of a variable. The "sizeof" result of a simple (non array)
variable is always 1.
An array with one dimension comprises a number of elements and the "sizeof" operator returns this quantity.
The code section below would therefore issue "5", as the array comprises four characters and the zero
terminator.
new msg[] = ’’Help’’
printf(’’%d’’, sizeof msg);
The "sizeof" operator always returns the number of entries even for a "packed" array. The code section below
also issues "5", as the variable comprises five entries even though it requires less memory space.
new msg{} = "Help"
printf(’’%d’’, sizeof msg);
For multi-dimensional arrays, the "sizeof" operator can return the number of elements for every dimension.
An element in the last (lowest) dimension is a single entry, while it is a sub-array in the highest dimension.
Please note that in the following code section, the "sizeof matrix" syntax returns the number of elements of the
higher dimension and that the "sizeof matrix[]" syntax issues the lower dimension of the two-dimensional
array. The code section issues three (higher dimension) and two (lower dimension).
new matrix[3][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } }
printf(’’%d %d’’, sizeof matrix, sizeof matrix[]);
The application of the "sizeof" operator on multi-dimensional arrays is particularly practical when it is used as
a standard value for function arguments.
168
Rev. 01