Today we’ll also see how memory can be arranged
differently: row-major vs column-major. 🧠💡
🧱 What is a 2D Array?
A 2D array is a table of elements with rows
and columns, declared like this:
data_type array_name[rows][columns];
Example:
int matrix[2][3]; // 2 rows × 3 columns
It has 6 elements in total.
✨ Initialization and Access
You can initialize like this:
int matrix[2][3] = {{1, 2, 3},{4, 5, 6}};
Access elements using two indices: matrix[row][column].
printf("%d", matrix[1][2]); // prints 6
✅ Expected Output: 6
🧠 Row-Major Order (C Default)
Row-major order stores one row after another
in memory.
Example:
matrix[2][3] = {{1,2,3},{4,5,6}}
Memory layout in C (row-major): 1 2 3 4 5 6
Example: Printing Addresses in C
#include <stdio.h>
int main() { int matrix[2][3] = {{10,20,30},{40,50,60}}; for(int i=0;i<2;i++){ for(int j=0;j<3;j++){ printf("Address of matrix[%d][%d] = %p\n", i,j,&matrix[i][j]); } } return 0;}
📍 Addresses increase row by row: matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[1][2]
🧩 Column-Major Order (Other Languages)
Some languages like Fortran and MATLAB use column-major
order, where one column is stored after another.
Example: matrix[2][3] = {{1,2,3},{4,5,6}}
Memory layout in column-major: 1 4 2 5 3 6
- First
column → matrix[0][0], matrix[1][0]
- Second
column → matrix[0][1], matrix[1][1]
- Third
column → matrix[0][2], matrix[1][2]
💡 In C, this does not
happen by default, but it’s useful to know for interfacing with other
languages or linear algebra libraries.
🧠 Visual Comparison
| Index | Row-Major (C) | Column-Major (Fortran / MATLAB) |
|---|---|---|
| matrix[0][0] | 1 | 1 |
| matrix[0][1] | 2 | 4 |
| matrix[0][2] | 3 | 2 |
| matrix[1][0] | 4 | 5 |
| matrix[1][1] | 5 | 3 |
| matrix[1][2] | 6 | 6 |
🔍 Key Takeaways
✅ C arrays use row-major
order by default
✅
Memory is contiguous, even though you see a 2D grid
✅
Column-major order exists in other languages — keep it in mind for cross-language
programming.
🧠 Mini Assignments
Declare a 3x2 integer matrix in C, fill values, and print each element with its memory address.
Observe how row-major order is followed.
Imagine the same matrix in column-major order. Write down manually the order in which memory would be stored.
🎯 Assignment 3:
Write a program to calculate the sum of each row and sum of each
column of a 2x3 matrix.
💬 Share your outputs and
observations with the ProgVeda Community! 🌟
Understanding memory layout helps you write faster, safer code and is
essential for future topics like pointers and dynamic arrays.
Post a Comment