2- D Array & Address Calculation using Row Major and Column Major

we can create an array of an array, known as a multidimensional array.
2-D Array:
  • Each element is represented as Arr[row][column], where Arr[][] is the 2D array.
  • It can also represent matrix
Example 1:
Int arr[4][5];
Where arr is the two dimensional array. It can hold maximum of 20 elements.



Example 2:
Int x[3][4];

Where x is the two dimensional array. It can hold maximum of 12 elements.

We can think of this array as a table with 3 rows and each row has 4 columns as shown below.


Address Calculation in 2-D Array:

While storing the elements of a 2-D array in memory, these are allocated contiguous memory locations. 
Therefore, a 2-D array must be linearized so as to enable their storage. 

There are two alternatives to achieve linearization: Row-Major and Column-Major.
  • Column by column called column-major order: fortan, MATLAB  
  • Row by row called row major order: C, C++, java, python






The address of a location in Row Major System is calculated using the following formula:

Row_M=Base Address+ Size of elements ( [Number of rows placed before ith row] * [Number Of elements placed in columns]+ [No. Of elements before jth element in ith row ])

Row_M= B+W( [i] * [n] + [j] )

Example:

Loc=[0,0]
Addr:[100]
Value:10
[0,1]
[101]
20
[0,2]
[102]
30
[1,0]
[103]
41
[1,1]
[104]
42
[1,2]
[105]
43
[2,0]
[106]
54
[2,1]
[107]
56
[2,2]
[108]
59


Find A[2][1]=?

Means where 43 is stored?


So, for finding memory location of particular element we must know about two things:
1. Base Address :
2. Size of Element:
These was given in example.


Row_M= B+W( [i] * [n] + [j] ) = 100+1(2*3+1)
= 100+7=107


Column Major:
The address of a location in Column Major System is calculated using the following formula:
Col_M=Base Addr.+ Size of elements ( [number of columns placed before jth col] *  [number of elements placed in rows]+ [No. Of elements before ith element in jth col. ])

Col_M= B+W( [j] * [m] + [i] )


Example:

Loc=[0,0]
Addr:[100]
Value:10
[0,1]
[103]
20
[0,2]
[106]
30
[1,0]
[101]
41
[1,1]
[104]
42
[1,2]
[107]
43
[2,0]
[102]
54
[2,1]
[105]
56
[2,2]
[108]
59


Find A[2][1]=?
Means where 43 is stored?

Solution:
Col_M= B+W( [j] * [m] + [i] ) = 100+1(1*3+2)
= 100+5=105

Post a Comment

0 Comments