Multidimensional Arrays in Memory
-
A 2D array is stored in the computer's memory one row following another.
-
The address of the first byte of memory is considered as the memory location of the entire 2D array.
-
Knowing the address of the first byte of memory, the compiler can easily compute to find the memory location of any other elements in the 2D array provided the number of columns in the array is known.
If each data value of the array requires B bytes of memory, and if the array has C columns, then the memory location of an element such as score[m][n] is (m*c+n)*B from the address of the first byte.
-
Note that to find the memory location of any element, there is no need to know the total number of rows in the array, i.e. the size of the first dimension. Of course the size of the first dimension is needed to prevent reading or storing data that is out of bounds.
-
Again one should not think of a 2D array as just an array with two indexes. You should think of it as an array of arrays.
-
Higher dimensional arrays should be similarly interpreted. For example a 3D array should be thought of as an array of arrays of arrays. To find the memory location of any element in the array relative to the address of the first byte, the sizes of all dimensions other than the first must be known.
-
Knowledge of how multidimensional arrays are stored in memory helps one understand how they can be initialized, and how they can be passed as function arguments.