In many programming languages, a two-dimensional array is implemented as a single, continuous one-dimensional array in memory. Each element of the array is stored in a contiguous block of memory, and the elements are accessed using a set of indices that represent the row and column of the element.

For example, consider the following two-dimensional array in C:

Copy codeint a[3][4] = {
  {1, 2, 3, 4},
  {5, 6, 7, 8},
  {9, 10, 11, 12}
};

This array is stored in memory as a single, continuous one-dimensional array of integers, like this:

Copy code[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

The two-dimensional indices [i][j] are translated into a single, one-dimensional index by the following formula:

Copy codeindex = i * numberOfColumns + j

In this case, the number of columns is 4, so the indices [i][j] are translated as follows:

Copy codea[0][0] => index = 0 * 4 + 0 = 0
a[0][1] => index = 0 * 4 + 1 = 1
a[0][2] => index = 0 * 4 + 2 = 2
a[0][3] => index = 0 * 4 + 3 = 3
a[1][0] => index = 1 * 4 + 0 = 4
a[1][1] => index = 1 * 4 + 1 = 5
...

This allows the array to be accessed using the familiar two-dimensional syntax, while still being stored in a continuous block of memory.

(Visited 2 times, 1 visits today)
Was this article helpful?
YesNo
Close Search Window