C
2-D Arrays & Matrices in C
🏠 Home Lecture 14: 2-D Arrays
Multi-Dimensional Data Structures

2-D Arrays & Matrices in C

A 2-D array is essentially an array of arrays. It organizes data into a tabular grid of Rows and Columns, widely used for image processing, grids, tables, and mathematical matrices.

How many total integer elements are allocated by int mat[3][4];?
matrix_intro.cDeclaration & Access
#include <stdio.h> int main(void) { // Declare and initialize 2x3 matrix int matrix[2][3] = { {10, 20, 30}, // Row 0 {40, 50, 60} // Row 1 }; // Access element at Row 1, Column 2 printf("matrix[1][2] = %d\n", matrix[1][2]); // 60 return 0; }
1

Row × Column Grid

Indexed via arr[row][col]. Row index 0 to R-1, Col index 0 to C-1.

2

Row-Major Storage

In RAM, entire Row 0 is stored first, followed immediately by Row 1, then Row 2.

3

Nested Loops

Outer loop iterates rows (i), inner loop iterates columns (j).

4

Address Formula

$ ext{Addr} = ext{Base} + (i imes C + j) imes ext{sizeof(type)}$.

Hardware Architecture

Row-Major Memory Order & Address Formula

Computer RAM is 1-dimensional. C maps 2D grid coordinates (i, j) into linear memory using the Row-Major Formula. Click any cell to inspect!

Interactive Row-Major Calculator

Selected: matrix[0][0] | Offset: k = 0 | RAM Address: 1000
Linear 1D Physical RAM Strip:

2D Logical Matrix Grid (Click Any Cell)

Click any coordinate (i, j) to highlight its mapped position in flat RAM:

💡 Row-Major vs Column-Major: C and C++ use Row-Major. Fortran and MATLAB use Column-Major.
Algorithmic Traversal

Matrix Traversal & Step-by-Step Tracer

Watch outer loop i hold constant while inner loop j iterates across every column of that row.

Interactive 2D Matrix Controls

Active 2D Grid Highlight:
Outer Loop: i = 0 | Inner Loop: j = 0 | Action: Ready
Standard Output:
Click "Next Step ▶" to start...
matrix_traversal.cActive Execution Line
for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { printf("%d ", mat[i][j]); } printf("\n"); }
Matrix Operations 1

Matrix Addition (C[i][j] = A[i][j] + B[i][j])

Two matrices can be added only if they have identical dimensions (M × N). Addition is performed element-by-element.

Matrix Addition Simulator

Step through each coordinate (i, j) and watch A[i][j] + B[i][j] compute into C[i][j]:

Coord: i = 0, j = 0
C[0][0] = A[0][0] (1) + B[0][0] (9) = 10
Calculation Log:
Ready. Click "Next Step ▶".

Live Matrix Addition: A + B = C

Matrix A
+
Matrix B
=
Result C
Matrix Operations 2

Matrix Transpose (AT)

The transpose of matrix A is formed by flipping its rows over its columns: B[j][i] = A[i][j]. An M × N matrix becomes N × M.

Transpose Simulator

Watch each row in matrix A turn into a column in matrix B:

Source: A[0][0] = 10 ➔ Dest: B[0][0]
Transpose Log:

Original A (2 × 3) ➔ Transposed AT (3 × 2)

Original A (2×3)
➔
Transposed AT (3×2)
Matrix Operations 3 (O(N³))

Matrix Multiplication (C = A × B)

Matrix multiplication requires 3 nested loops: Row i of A dot-products with Column j of B across shared dimension k.

3-Nested-Loop Dot Product Visualizer

A (Row i)
×
B (Col j)
=
C[i][j]
Cell C[0][0] | Multiplier: k = 0
A[0][0] × B[0][0]
Step Log:
matrix_multiply.c3 Nested Loops
for (int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { C[i][j] = 0; for (int k = 0; k < c1; k++) { C[i][j] += A[i][k] * B[k][j]; } } }
Special Properties

Symmetric Matrices & Principal Diagonal Trace

A square matrix is Symmetric if A = AT (A[i][j] == A[j][i]). The Trace is the sum of main diagonal elements Sum of A[i][i].

Matrix Properties Inspector

Principal Diagonal: [4, 5, 6] | Trace = 15
Status: Symmetric Matrix (A == AT)
Pairwise Check Log:

Diagonal (🟡 Gold) & Transpose Pairs

✨ Notice how elements mirrored across the golden main diagonal (i == j) are identical in a symmetric matrix!
Computer Systems & Performance

Cache Locality: Row-Major vs Column-Major

Traversing memory sequentially utilizes CPU cache lines with spatial locality (⚡ Hits). Non-sequential stride causes CPU cache stalls (🛑 Misses)!

CPU L1 Cache Simulator

4×4 Matrix Memory
CPU L1 Cache Line (4 slots)
Ready
⚡ Hits: 0 | 🛑 Misses: 0 | Hit Rate: 0%
Select pattern and click "Step Access ▶" to inspect CPU cache behavior.
cache_locality.cHardware Execution Tracer
// ✅ FAST: Sequential Memory Access (Stride = 1) for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { sum += matrix[i][j]; // ⚡ Cache Line Hit! } }
CPU Memory Bus Log:
Click "Step Access ▶" to start cache simulation...
Critical Traps

Common 2-D Array Pitfalls & Bugs

Avoid the top compilation errors and runtime memory bugs encountered when working with multi-dimensional arrays.

1. Index Inversion Bug [j][i]

Confusing row index with column index leads to transpose mistakes or immediate segmentation fault.

int m[3][5]; m[4][2] = 10; // ⚠️ BUG: Row 4 out of bounds (0..2)

2. Omitting Column Dimension in Parameters

C compiler MUST know column width to calculate $(i imes C + j)$. Column width is mandatory!

void print(int m[][]); // ❌ Compile Error void print(int m[][4]); // ✅ Correct

3. Incompatible Matrix Multiplication

Multiplication of (R1 × C1) with (R2 × C2) is valid ONLY if C1 == R2.

// (2 × 3) multiplied by (3 × 4) ➔ (2 × 4) if (colsA != rowsB) printf("Cannot Multiply!\n");

4. Large Stack Allocation Overflow

Declaring huge 2D arrays on the stack will instantly trigger a stack overflow.

int big[5000][5000]; // ⚠️ 100MB on stack (Crash!)
Question 1 of 5
Loading quiz...