Data Structures Notes
Data Structures Notes
Suppose we have a 2D array Data with dimensions X=4 and Y=4 with the
following values:
There are two ways of storing a 2D array in memory, Row major and Column
Major. In Row major, values are stored row after row:
To access the values of the elements the values of x and y would change like
this:
In the above formula, everything is the same as the 1D array’s formula except
“(x * Y + y)”. This part of the formula is used to calculate the slot number of the
elements.
If we have an array with dimensions [X][Y], we can calculate the slot numbers
for the elements using the formula:
xY + y, where x = 0, … , X-1 and y = 0, … , Y-1
Now the generalized formula for calculating the memory address of an element
in an n-dimensional array is:
Base address + (slot number formula) + sizeof(data-type)
The formula for the slot number in an n-dimensional array basically follows the
rule that each index I0,I1,I2…In-1 depends on the sizes (S0,S1…) that come
before it. So In-1 doesn’t depend on anything, In-2 depends on Sn-1, In-3
depends on Sn-1 and Sn-2 and so on.
So the general formula to calculate slot number will be:
(I1 * S2 * S3 … * Sn-1) + (I2 * S3 * S4 … Sn-1) + (I3 * S4 * S5 … Sn-1) … (I1 *
Sn-1) + (In-1)
n−1 n−1
∑ 𝐈𝑗 ∗ ∏ 𝐒𝑘
𝑗=0 𝑘=𝑗+1