Ads block

Banner 728x90px

Implementation of 2D Array

A two-dimensional array can be implemented in a programming language in two ways:

1. Row-major implementation
2. Column-major implementation


Row-Major Implementation

Row-major implementation is a linearization technique in which elements of array are reader from the keyboard row wise i.e., the complete first row is stored, then the complete second row is stored and so on.


Note: Matrix form is a logical representation of the array. It is not the actual way in which two-dimensional array is stored.



Address of element in Row major

The computer does not keep the track of all elements of the array, rather, it keeps a base address and calculates the address of required elements when needed.

It calculates this by the following relation:

Address of element a[i][j] = B + W (n (i-L1)+(j-L2))

Where B is the base address of the array
W is size of each element,
n is the number of columns (i.e.,U2 - L2)
L1 is lower bound of row,
L2 is lower bound of column



Column Major Implementation


In column major implementation memory allocation is done column by column i.e., first the elements of the complete first column is stored, then elements of complete second column is stored, and so on.

The storage can be clearly understood by arranging array as matrix


Address of element in Column major

In Column major implementation address of an element a[i][j] is given by the relation:

Address of element a[i][j] = B + W (m (j-L2)+(i-L1))

Where m is the number of rows (i.e., U1 - L1).
B is the base address of the array
W is size of each element,
L1 is lower bound of row,
L2 is lower bound of column