Column-major Order in Data Structure

Column-major order is another way to store a matrix in memory, where the elements of each column are stored in contiguous memory locations, and the columns themselves are also stored in contiguous memory locations.

To create and access a matrix in column-major order in C, you can use a one-dimensional array and perform index calculations to access the elements of the matrix. Here is an example code that creates a 3x3 matrix in column-major order:

```c
#include <stdio.h>

#define ROWS 3
#define COLS 3

int main() {
    int matrix[ROWS * COLS] = {1, 4, 7, 2, 5, 8, 3, 6, 9};

    // accessing elements of the matrix
    printf("Element at (1, 2) = %d\n", matrix[2 * ROWS + 1]); // prints 6
    printf("Element at (2, 0) = %d\n", matrix[0 * ROWS + 2]); // prints 7

    return 0;
}
```

In this code, we have defined a matrix with 3 rows and 3 columns using a one-dimensional array `matrix[ROWS * COLS]`. The elements of the matrix are initialized with initial values using the brace initialization.

To access the elements of the matrix, we use the indices of the desired element. In column-major order, the column index comes first, followed by the row index. So, `matrix[2 * ROWS + 1]` represents the element at column 2 and row 1, which has a value of 6.

Similarly, `matrix[0 * ROWS + 2]` represents the element at column 0 and row 2, which has a value of 7. The output of the program will be:

```
Element at (1, 2) = 6
Element at (2, 0) = 7
```

Note that in column-major order, the memory addresses of the elements of a column are contiguous. The memory address of an element with column index `j` and row index `i` can be calculated using the following formula:

```
address = base_address + (j * ROWS + i) * element_size
```

where `base_address` is the memory address of the first element of the matrix, `j` is the column index, `i` is the row index, `ROWS` is the number of rows in the matrix, and `element_size` is the size of each element in bytes.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext