Open In App

Calculating the address of an element in an N-dimensional array

N-Dimensional Arrays: The N-Dimensional array is basically an array of arrays. As 1-D arrays are identified as a single index, 2-D arrays are identified using two indices, similarly, N-Dimensional arrays are identified using N indices. A multi-dimensional array is declared as follows:

int NDA[S1][S2][S3]……..[SN];



Explanation:

Address Calculation of N-Dimensional Arrays:



Assumptions:

Explanation:

UpperBound – LowerBound +1

For address calculation, the lower bounds are t1, t2, t3…….tN. There exist two ways to store the array elements:

The Column Major formula:

Address of NDA[I1][I2]. . . [IN] = BAd + W*[((…ENSN-1+ EN-1 )SN-2 +… E3 )S2+ E2 )S1 +E1]

  • BAd represents the base address of the array.
  • W is Storage Size of one element stored in the array (in byte).
  • Also, Ei is given by E = li – ti, where li and ti are the calculated indexes (indices of array element which needs to be determined) and lower bounds respectively.

The Row Major formula:

Address of NDA[I1][I2]. . . .[lN] = BAd + W*[((E1S2 + E2 )S3 +E3 )S4 ….. + EN-1 )SN + EN]

The simplest way to learn the formulas:

For row-major: If width = 5, the interior sequence is E1S2 + E2S3 + E3S4 + E4S5 + E5 and if width = 3, the interior sequence is E1S2 + E2S3 + E3. Figure out the pattern in the order and follow four basic steps for the formula of any width:

E1S2 + E2)S3 + E3)S4 + E4)S5 + E5).

((((E1S2 + E2)S3 + E3)S4 + E4)S5 + E5).

The approach is similar for the Column Major but the pattern of the interior sequence is reverse of the row-major pattern. 

For column-major: If width =5, the interior sequence is E5S4 + E4S3 + E3S2+ E2S1 + E1.

Example: Let’s take a multi-dimensional array A[10][20][30][40] with the base address 1200. The task is to find the address of element A[1][3][5][6].

Here, BAd = 1200 and width = 4.
S1 = 10, S2 = 20, S3 = 30, S4 = 40

Since the lower bounds are not given, so lower bounds are assumed to be zero.
E1 = 1 – 0 = 1; 
E2 = 3 – 0 = 3; 
E3 = 5 – 0 = 5;
E4 = 6 – 0 = 6.

Any of the techniques (Row-major or column-major) can be used for calculating the answer (unless specified). 
By applying the formula for row-major, directly write the formula as:

A[1][3][5][6] = 1200 + 4(((1 × 20 + 3)30 +5)40 + 6) 

 =1200 +4((23 × 30 +5)40 +6) 

=1200 + 4(695 × 40 + 6) 

=1200 + (4 × 27806) 

=112424.


Article Tags :