Array Indexing Errors

Summary: The first C array subscript is 0.

If you're used to a language that has different subscripting rules, it's easy to forget that the first subscript of a C array is 0 and the last subscript is 1 less than the number used to declare the array. Here's an example:

int i_array[4] = { 3, 55, 600, 12 };

main()

{

int count;

for( count = 1; count < 5; count++ ) /* Error! */

printf( "i_array[%d] = %d\n", i_array[count] );

}

The for loop in the above program starts at i_array[1] and ends at i_array[4]. It should begin with the first element, i_array[0] and end at the last, i_array[3]. The following corrects the error.

for( count = 0; count < 4; count++ )

printf( "i_array[%d] = %d\n", i_array[count] );