Friday, April 19, 2013

memory allocation for 2D array

the memory of a computer is linear and not a matrix like a 2D array. So, the elements of the array are stored either by row, called "row-major", or by column, called "column-major". Row-major order is used most notably in C and C++ during static declaration of arrays.
In C, since the length of each row is always known, the memory can be filled row one row at a time, one after the other.
Example:
a[i][j] =
1 2 3 4 5 6 7 8 9
Representation in the memory: In row-major: 1 2 3 4 5 6 7 8 9 In column-major: 1 4 7 2 5 8 3 6 9
Address calculation of an element:

Row-Major :
addr (i,j) = B + W * ( Nc * (i - Lr) + (j-Lc) )