Nearby lessons
58 of 124C - Two Dimensional Array
The 2D array is a table of rows and columns — C's matrix type. Learn declaration, initialisation, nested-loop traversal, row-major memory layout, and matrix addition and transpose.
Declaring a 2D Array
Two sets of brackets: the first is the number of rows, the second the number of columns:
Initialising with Nested Braces
Group each row in its own set of braces. It compiles without the inner braces too, but the nested form documents the shape:
Printing a Matrix with Nested Loops
The outer loop selects the row; the inner loop walks that row's columns. The newline goes in the outer loop:
Row-Major Storage
Memory is one-dimensional, so C flattens the table. It stores all of row 0, then all of row 1, and so on — this is called row-major order:
The Address Formula
a[i][j] sits at position i * columns + j in the flat block.So a[1][0] in a 3-column array is at flat position 1*3 + 0 = 3 — the fourth element. That is why the column count must be given when passing a 2D array to a function: without it, C cannot compute where a row begins.
Reading a Matrix from the User
Two nested loops with scanf. Remember the & before a[i][j]:
Matrix Addition
Add matching positions. Both matrices must have identical dimensions:
Transpose — Swapping Rows and Columns
The transpose of an m×n matrix is n×m. Simply write a[i][j] into t[j][i]:
Passing a 2D Array to a Function
You may omit the row count, but the column count is mandatory:
Common Mistakes
- Writing
a[i, j]— that is the comma operator; it evaluates toa[j]. Always usea[i][j]. - Omitting the column count in a parameter —
void f(int a[][])will not compile. - Swapping the loop bounds — using the column count for rows silently reads out of bounds.
- Transposing in place on a non-square matrix — the result has different dimensions, so you need a second array.
- Printing the newline in the inner loop — puts every element on its own line.
int a[3][4] is 3 rows of 4 columns, so the valid indexes are a[0..2][0..3]. Mixing these up is the most common 2D array bug.- Syntax: type name[rows][columns].
- arr[i][j] means row i, column j — both start at 0.
- C stores 2D arrays in row-major order: row 0 entirely, then row 1.
- The outer loop walks rows, the inner loop walks columns.
- When passing a 2D array to a function, the column count is required.