Row Major Order and Column Major Order in C
For Complete YouTube Video: Click Here
In this class, we will try to understand Row Major Order and Column Major Order in C.
We have clearly understood two-dimensional arrays in our previous classes.
As discussed in our previous class, we can store a two-dimensional array’s values in row-major order or column-major order.
Table of Contents
Row-Major order or Column-Major order
For example, consider the two-dimensional array declarations as shown in the image below.
Row-Major Order
If the compiler is implemented using row-major order, then the values will get stored in the memory, as shown in the image below.
In the above image, the values 1, 2, 3, 4, 5, and 6 are stored at starting memory locations 50, 54, 58, 62, 66, and 70 (Assume int takes 4 bytes of space).
For example, if we want to access value two from memory, we must declare a[0][1].
This declaration is made under the visualization of a two-dimensional array as a matrix, as shown in the image below.
Now this declaration has to be converted into a memory address.
How will the compiler convert the [0][1] to a memory address?
The compiler uses the formula given below to convert it into a memory address.
In the above formula based upon our example, i and j are the array indexes; in this case, it is zero and one.
Also, m and n are the matrix indexes; in this case, it is two and three.
The base address is 50, and the size of the int is 4 bytes.
By substituting the corresponding values, we will get the memory address as 54.
((0*3) + 1) * 4 + 50 = 54.
Column Major Order
If the compiler is implemented by column-major order, the array elements will be stored in the memory, as shown in the image below.
Similar to the above discussion on row-major order, the formula for column-major order is shown below.