1.

What do you understand by row-major order and column-major order of arrays? Derive their formulae for calculating the address of an array element in terms of the row-number, column-number and base address of array. 

Answer»

A two dimensional array is declared similar to the way we declare a one-dimensional array except that we specify the number of elements in both dimensions. For example,

int grades[3][4];

The first bracket ([3]) tells the compiler that we are declaring 3 pointers, each pointing to an array. We are not talking about a pointer variable or pointer array. Instead, we are saying that each element of the first dimension of a two dimensional array reference a corresponding second dimension. In this example, all the arrays pointed to by the first index are of the same size. The second index can be of variable size. For example, the previous statement declares a two-dimensional array where there are 3 elements in the first dimension and 4 elements in the second dimension.

Two-dimensional array is represented in memory in following two ways:

1. Row major representation: To achieve this linear representation, the first row of the array is stored in the first memory locations reserved for the array, then the second row and so on.

2. Column major representation: Here all the elements of the column are stored next to one another.

In row major representation, the address is calculated in a two dimensional array as per the following formula

The address of a[i] [j] =base (a) + (i*m+ j) * size

where base(a) is the address of a[0][0], m is second dimension of array a and size represent size of the data type. 

Similarly in a column major representation, the address of two dimensional array is calculated as per the following formula

The address of a[i] [j] = base (a) + (j*n +i) * size

Where base (a) is the address of a [0] [0], n is the first dimension of array a and size represents the size of the data type.



Discussion

No Comment Found

Related InterviewSolutions