← Back to C Course | Chapter 6: Arrays & Strings | Lesson 4 of 8

C Multi-dimensional Arrays

Two-Dimensional Arrays

Internally, a 2D array is still stored as one contiguous block of memory in row-major order, meaning an entire row is stored before the next row begins -- this layout is why looping row-by-row is more cache-friendly than column-by-column.

Example: Two-Dimensional Arrays

c
#include <stdio.h>
int main() {
	int grid[2][2] = {{1, 2}, {3, 4}};
	printf("%d", grid[1][0]);
	return 0;
}

Initializing 2D Arrays

When you initialize with nested braces like {{1,2},{3,4}}, each inner group fills one row in order; if you provide fewer values than a row needs, the remaining elements in that row are automatically set to zero.

Example: Initializing 2D Arrays

c
#include <stdio.h>
int main() {
	int grid[2][2] = {{1, 2}, {3}};
	printf("%d", grid[1][1]);
	return 0;
}

Accessing Elements in 2D Arrays

grid[2][3] reads as 'row 2, column 3' -- mixing up the order is a frequent source of bugs, especially when translating between mathematical matrix notation (which some fields write row-first, others column-first) and code.

Example: Accessing Elements in 2D Arrays

c
#include <stdio.h>
int main() {
	int grid[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
	printf("%d", grid[2][3]);
	return 0;
}

Modifying Elements in 2D Arrays

Just like 1D arrays, updating grid[i][j] only changes that single cell; there's no built-in way to reassign an entire row at once except by looping or using memcpy() on that row's contiguous memory.

Example: Modifying Elements in 2D Arrays

c
#include <stdio.h>
int main() {
	int grid[2][2] = {{1, 2}, {3, 4}};
	grid[0][1] = 99;
	printf("%d", grid[0][1]);
	return 0;
}

Looping Through 2D Arrays

The outer loop variable typically represents the row and the inner loop the column (or vice versa, as long as you're consistent) -- getting the loop bounds wrong for either dimension is easy to do and will either skip data or read out of bounds.

Example: Looping Through 2D Arrays

c
#include <stdio.h>
int main() {
	int grid[2][2] = {{1, 2}, {3, 4}};
	for (int row = 0; row < 2; row++) {
		for (int col = 0; col < 2; col++) {
			printf("%d ", grid[row][col]);
		}
	}
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.