Nearby lessons
59 of 124C - Multidimensional Array
Multidimensional arrays in C — arrays with three or more dimensions. Learn the 3D array declaration, how to visualise it as a stack of tables, its memory layout, and when the extra dimensions are worth it.
Beyond Two Dimensions
C puts no practical limit on dimensions — the standard guarantees at least 12. Each pair of brackets adds a level:
| Declaration | Dimensions | Mental picture | Elements |
|---|---|---|---|
int a[5] | 1 | A row | 5 |
int a[3][4] | 2 | A table | 12 |
int a[2][3][4] | 3 | 2 stacked tables | 24 |
int a[2][2][3][4] | 4 | 2 groups of 2 tables | 48 |
int a[2][3][4] is 2 tables, each with 3 rows, each row holding 4 numbers.Declaring and Initialising a 3D Array
Nest the braces one level deeper than for a 2D array — an outer group per table, an inner group per row:
Traversing with Three Nested Loops
One loop per dimension. The outermost walks tables, the middle walks rows, the innermost walks columns:
Memory Layout — Rightmost Index Varies Fastest
Memory is still a single flat block. C fills it by incrementing the last index first, then the middle, then the first:
The Flat Position Formula
For int a[D1][D2][D3], element a[i][j][k] lives at flat offset:
(i × D2 × D3) + (j × D3) + k
A Practical Example — Marks by Class
Three dimensions map naturally onto real data: class → student → subject:
Passing to a Function
Only the first dimension may be omitted. All the rest are needed so C can compute offsets:
When Not to Use Them
Multidimensional arrays are simple but rigid. Watch out for these limits:
- Memory grows multiplicatively —
int a[100][100][100]is a million ints, about 4 MB, and will overflow the stack as a local. - Hard to read past three dimensions —
a[i][j][k][l][m]is a maintenance problem. - Every dimension is fixed at compile time — a jagged structure needs an array of pointers instead.
- All dimensions must be stated in parameters — that couples your functions to exact sizes.
int a[500][500][10]; (about 10 MB) overflows it immediately. Declare big arrays as static, make them global, or allocate them with malloc.- Syntax: type name[d1][d2][d3]... — C allows at least 12 dimensions.
- Read int a[2][3][4] as 2 tables of 3 rows and 4 columns.
- Total elements = the product of all dimensions.
- Storage is row-major: the rightmost index varies fastest.
- All dimensions except the first are required in a function parameter.