#include <stdio.h> #include <stdlib.h> /* Puzzle D01 -- fill an N by M integer array with zeros and print it out. */ int main(int argc, char *argv[]) { const int Nrows = 3, Mcols = 5 ; int x[Nrows][Mcols] ; int count = 0; /* Values to copy to the array */ int r, c; /* row and column indexes for the array */ /* Fill the array with ascending integers */ for ( r=0; r<Nrows; r++ ) for ( c=0; c<Mcols; c++ ) x[r][c] = count++ ; /* Print out the array */ for ( r=0; r<Nrows; r++ ) { for ( c=0; c<Mcols; c++ ) printf("%2d ", x[r][c] ); printf("\n"); } printf("\n"); system("PAUSE"); return 0; }
Comments: Arrays are stored in main memory in row-major order, which means that the elements of a row are stored in sequence in memory.
The above program stores integers in order into the array. Conceptually the above 3x5 array looks like this:
Column | |||||
---|---|---|---|---|---|
row | 0 | 1 | 2 | 3 | 4 |
0 | 0 | 1 | 2 | 3 | 4 |
1 | 5 | 6 | 7 | 8 | 9 |
2 | 10 | 11 | 12 | 13 | 14 |
However, in main memory the elements are stored like this (assume that memory addresses increase to the right):
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
Because of this, code that accesses every element of a 2D array should be written, as follows, so that elements are accessed in sequence through memory:
for ( r=0; r<Number_Of_Rows; r++ ) { for ( c=0; c<Number_Of_Columns; c++ ) { ... do something with element[r][c] ... } }