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]) {
. . .
}
The memory for this array could be visualized as in the diagram to the right, which identifies a few cells by their subscripts.
2D array memory representation
2D array memory representation
int **a;
int a[3][2]
a--base addr---> a[0]/*a 1 2
a[1]/(*a)+1 3 4
a[2]/(*a)+2 5 6
rows = sizeof(a)/sizeof(*a) or /sizeof(*a);
f(int **p);
f(int p[][2]);
Because memory is addressed linearly, a better representation is like the diagram to the left.
Computing the address of an array element
C++ must compute the memory address of each array element that it accesses. C++ does this automatically, but it helps to understand what's going on "under the hood". Assume the following declaration:
char a[ROWS][COLS]; // assume ROWS and COLS are const ints
Because arrays are laid out in memory by row, each row length is COLS (the number of columns is the size of a row). Let's assume that you want to find the address of a[r][c]. The baseAddress of the array is the address of the first element. The rowSize is COLS in the above example. The elementSize is the number of bytes required to represent the data (typically 1 for char, 4 for int, 4 for float, and 8 for double.
address = baseAddress + elementSize * (r*rowSize + c);
Note
* The number of rows (ROWS) is not used in the computation.
* Because the number of rows is not used, there is no need to pass it when declaring a formal array parameter for a two-dimension array.
Wednesday, August 19, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment