Omitting an Array Subscript in Multidimensional Arrays

Summary: Enclose each subscript in its own set of brackets.

Programmers who know QuickBasic, QuickPascal, or FORTRAN may be tempted to place more than one array subscript in the same pair of brackets. In C, each subscript of a multidimensional array is enclosed in its own pair of brackets:

int i_array[2][2] = { { 12, 2 }, { 6, 55 } };

main()

{

printf( "%d\n", i_array[ 0, 1 ] ); /* Error! */

}

In the preceding example, the expression

i_array[ 0, 1 ]

does not access element 0,1 of i_array . Here is the correct way to refer to that array element:

i_array[0][1]

Interestingly, the deviant array reference doesn't cause a syntax error. As mentioned in Chapter 6, “Operators,” it's legal to separate multiple expressions with a comma operator, and the final value of such a series is the value of the rightmost expression in the group. Thus, the expression

i_array[ 0, 1 ]

is equivalent to this one:

i_array[ 1 ];

Both expressions give an address, not the value of an array element.