Sams Teach Yourself C in 21 Days

(singke) #1
To describe this differently, the left subscript is declared as 10, but the forloop
usesxas the left subscript. xis incremented with three values. The right subscript
is declared as 3, but the second forloop uses yas the right subscript. yis incre-
mented with 10 values. This can cause unpredictable results. You can fix this pro-
gram in one of two ways. The first way is to switch xandyin the line that does the
initialization:
int x, y;
int array[10][3];
int main( void )
{
for ( x = 0; x < 3; x++ )
for ( y = 0; y < 10; y++ )
array[y][x] = 0; /* changed */

return 0;
}
The second way (which is recommended) is to switch the values in the forloops:
int x, y;
int array[10][3];
int main( void )
{
for ( x = 0; x < 10; x++ ) /* changed */
for ( y = 0; y < 3; y++ ) /* changed */
array[x][y] = 0;
return 0;
}


  1. This, I hope, was an easy bug to bust. This program initializes an element in the
    array that is out of bounds. If you have an array with 10 elements, their subscripts
    are 0 to 9. This program initializes elements with subscripts 1 through 10. You
    can’t initialize array[10], because it doesn’t exist. The forstatement should be
    changed to one of the following examples:
    for( x = 1; x <=9; x++ ) / initializes 9 of the 10 elements /
    for( x = 0; x <= 9; x++ )
    Note that x <= 9is the same as x < 10. Either is appropriate; x < 10is more
    common.

  2. The following is one of many possible answers:
    / Using two-dimensional arrays and rand() /
    #include <stdio.h>
    #include <stdlib.h>
    / Declare the array /


848 Appendix F

49 448201x-APP F 8/13/02 11:22 AM Page 848

Free download pdf