Wednesday, September 1, 2010

2-Dimensional Arrays

Data that is in rows and columns is usually stored in 2-dimensional arrays.

Declaring of 2-dimensional arrays

Two-dimensional arrays are declared by specifying the number of rows then the number of columns.
int  a[30][10];  // declares an int array of 30 rows and 10 columns.
char ticTacToeBoard[3][3]; // three rows and three columns of chars.

Initializing 2-dimensional arrays

Unless specified, all initial values of arrays are garbage. You can specify initial values by enclosing each row in curly braces like this:
char ticTacToeBoard[3][3] = {{'x', 'x', 'o'},
{'o', 'o', 'x'},
{'x', 'o', ' '}
};
If some elements are omitted in the initialization list, they are set to zero.

Subscripting 2-dimensional arrays

Write subscripts as x[row][col]. Passing over all elements of a two-dimensional array is usually done with two nested for loops.
// clear the board
for (int row=0; row<3; row++) {
for (int col=0; col<3; col++) {
ticTacToeBoard[row][col] = ' ';
}
}

Passing 2-dimensional arrays as parameters

C++ doesn't care about bounds, but it needs to compute the memory address given the subscripts (see below). To do this it needs to know the row width (number of columns). Therefore formal 2-dimensional array parameters must be declared with the row size, altho the number of rows may be omitted. For example,
void clearBoard(ticTacToeBoard[][3]) {
. . .
}

No comments:

Post a Comment