2D Arrays in Compilers

  • 2D arrays might be visualized in rows and columns by humans, but the actual memory allocated will be linear, like a single dimensional array.

  • How are elements in 2D arrays stored in a single dimension array? There are two methods of mapping:

  • Row major mapping,

  • Column major mapping.

  • Just like with regular arrays, the compiler uses a formula to access the address within a 2D array.

  • The formula for row major mapping is: Address(A[i][j]) = Base Address + (i * Num of Columns + j) * Data Type Size.

  • The formula for column major mapping is Address(A[i][j]) = Base Address + (j * Num of Rows + i) * Data Type Size.

  • Both has the same number of operations, in terms of time, both are equally efficient. In C / C++ the row major formula is used.