Previously, I stated that when defining a two-dimensional array, the first size is the number of rows, and the second is the number of columns. I'm deliberately using the labels "rows" and "columns" because their meanings are well-established and understood in the context of tables. But does choosing one array index order over the other make a difference? Are we forced to use rows × cols, or can we define it as cols × rows? Again, I'm deliberately using a multiplication notation here to make a point: multiplication is commutative, so the product rows × cols is the same as cols × rows: both create the same number of elements. This observation suggests that there is some ambiguity, or, depending on your point of view, some flexibility with the index order.
int array[2][3]; int array[3][2]; |
Figure 1 suggests that if we consistently use the same index order throughout the program, either order will work - at least in many cases. Nevertheless, I assert that the "correct" index order is rows × cols
or array[rows][cols]
. My view may seem capricious in light of what we have just seen, so permit me to offer a few reasons for my assertion.
argv
, with the information. argv
is an array of string pointers, and each string is an array of characters. A two-dimensional notation, argv[row][col]
, is used to access individual characters in the array. The operating system defines the index order, and programmers cannot change it. (Command line arguments are addressed in detail in the next chapter.)
1 2 3 4 5 6 7 8 9 10 11 12 |
int array[3][4] int array[4][3] |
(a) | (b) |
#include <iostream> using namespace std; void print_row(int* row, int size) { for (int i = 0; i < size; i++) cout << row[i] << endl; } int main() { int array[3][4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; // row first //int array[4][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; // columns first print_row(array[2], sizeof(array[2]) / sizeof(int)); // see the note below return 0; } |
|
(c) | |
9 10 11 12 |
7 8 9 10 |
(d) | (e) |
In summary, some programs will work regardless of the index order as long as the indexes are used consistently throughout the program. But it is customary to use rows x cols
or [rows][cols]
and this order always works. So, throughout this textbook, rows first, followed by columns, is the "correct" order.