02. 2D & Multidimensional Matrices in C
🟡 Difficulty: Intermediate | Grid Layouts, Row-Major Order & Matrix Operations
📖 Definition
A 2D array (matrix) in C is an array of 1D arrays, logically structured into rows and columns. In RAM physical memory, all elements are laid out sequentially in Row-Major Order (elements of row 0 come first, followed by row 1, row 2, etc.).
🎯 Why It Is Used
- Grid & Board Representations: Essential for representing game boards (chess, tic-tac-toe), images (pixels), and mathematical matrices.
- Linear Address Translation: The compiler automatically converts 2D bracket syntax
matrix[r][c]into 1D memory offset arithmetic:*(BaseAddress + (r * COLS) + c).
⚙️ How It Works: Row-Major Address Formula
Given int matrix[ROWS][COLS], the physical memory byte offset for element matrix[r][c] is calculated as:
Physical Address = BaseAddress + ((r * COLS) + c) * sizeof(ElementType)
Notice that the total column count (COLS) is mandatory for index calculations!
📝 Syntax
// 1. Declaration with explicit Row and Column dimensions
int grid[3][4]; // 3 rows, 4 columns (12 total integers)
// 2. Nested Initializer List
int matrix[2][3] = {
{10, 20, 30}, // Row 0
{40, 50, 60} // Row 1
};
// 3. Omitting outer row dimension (compiler infers 2 rows)
int matrix[][3] = {
{1, 2, 3},
{4, 5, 6}
}; // Outer row count inferred automatically; inner column dimension MANDATORY!
🔀 Multidimensional (3D) Arrays
C supports 3D or higher dimensions (e.g. int cube[depth][rows][cols]). A 3D array is represented physically as a contiguous 1D sequence using nested offset multiplications.
🌱 Beginner Example
#include <stdio.h>
int main(void) {
int grid[2][3] = {
{5, 10, 15},
{20, 25, 30}
};
printf("=== 2D Grid Elements ===\n");
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
printf("grid[%d][%d] = %2d ", r, c, grid[r][c]);
}
printf("\n");
}
return 0;
}
🌼 Intermediate Example: Matrix Addition & Transposition
#include <stdio.h>
#define N 3
int main(void) {
int A[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int B[N][N] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int Sum[N][N];
printf("=== Matrix Addition (A + B) ===\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
Sum[i][j] = A[i][j] + B[i][j];
printf("%3d ", Sum[i][j]);
}
printf("\n");
}
return 0;
}
🌲 Advanced Example: Standard Matrix Multiplication O(N^3)
#include <stdio.h>
#define R1 2
#define C1 3
#define R2 3
#define C2 2
int main(void) {
int A[R1][C1] = {{1, 2, 3}, {4, 5, 6}};
int B[R2][C2] = {{7, 8}, {9, 1}, {2, 3}};
int Result[R1][C2] = {0};
// Matrix Multiplication: Result[i][j] = sum(A[i][k] * B[k][j])
for (int i = 0; i < R1; i++) {
for (int j = 0; j < C2; j++) {
for (int k = 0; k < C1; k++) {
Result[i][j] += A[i][k] * B[k][j];
}
}
}
printf("=== Matrix Product Result (2x2) ===\n");
for (int i = 0; i < R1; i++) {
for (int j = 0; j < C2; j++) {
printf("%4d ", Result[i][j]);
}
printf("\n");
}
return 0;
}
🔍 Line-by-Line Explanation
int Result[R1][C2] = {0};: Zero-initializes product matrix to accumulate dot products.Result[i][j] += A[i][k] * B[k][j];: Performs row-by-column inner product summation.int matrix[][3] = ...: Inner dimension[3]is mandatory so compiler knows row stride width.
💻 Expected Terminal Output
=== 2D Grid Elements ===
grid[0][0] = 5 grid[0][1] = 10 grid[0][2] = 15
grid[1][0] = 20 grid[1][1] = 25 grid[1][2] = 30
=== Matrix Addition (A + B) ===
10 10 10
10 10 10
10 10 10
=== Matrix Product Result (2x2) ===
31 19
85 55
⚠️ Common Mistakes & Pitfalls
- Omitting Inner Column Dimension in Declarations: Writing
int arr[][] = ...orvoid fn(int arr[][])causes compilation errors. Column width MUST be specified! - Row-Column Index Order Confusion: Writing
matrix[col][row]instead ofmatrix[row][col]causes index out-of-bounds errors and memory corruption.
📌 Important Rules & Limitations
- 2D arrays are stored sequentially in Row-Major order in physical RAM.
- When declaring or passing 2D arrays, all dimensions except the leftmost (outermost) dimension must be fixed constants.
🌐 Multilingual Explanation: English
A 2D array is an array of arrays stored in row-major order. The column dimension must always be specified so the compiler can perform linear offset calculations.
🌐 Multilingual Explanation: Hindi (Roman Script)
2D array row-major order mein RAM mein store hota hai. Declare ya pass karte waqt columns ki dimension batana compulsory hota hai.
🌐 Multilingual Explanation: Marathi (Roman Script)
2D array RAM madhye row-major order madhye contiguous store hoto. Columns chi dimension tharvane bandhanakarak aste.
❓ Practice Questions
- What formula translates a 2D index
[r][c]into a 1D linear offset? - Why must the column dimension be specified when declaring or passing a 2D array?
- What is row-major memory order?
🚀 Practical Coding Challenge
Write a C program named matrix_transpose.c that initializes a 3x3 matrix, prints it, and then computes and displays its transposed matrix (swapping matrix[i][j] with matrix[j][i]).
🧭 Navigation & Breadcrumbs
← Previous: 01. 1D Arrays | Module 09 Guide | Next: 03. Passing Arrays to Functions →