C - Multi-Dimensional Arrays
Overview
Multi-dimensional arrays are arrays of arrays. The most common are two-dimensional arrays, often used to represent matrices or tables.
Learning Objectives
- Declare and index 2D arrays.
- Understand row-major order and passing 2D arrays to functions.
Prerequisites
Declaration
int matrix[3][4]; // 3 rows, 4 columns
Example
#include <stdio.h>
int main(void) {
int mat[2][3] = {{1,2,3},{4,5,6}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
More Examples
#include <stdio.h>
void print2D(int a[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) printf("%d ", a[i][j]);
printf("\n");
}
}
Checks for Understanding
- How do you pass a 2D array to a function?
Show answer
Specify all but the first dimension: void f(int a[][N], int rows)
.
Expected Output
For the 2x3 example:
1 2 3
4 5 6
Common Pitfalls
- When passing a 2D array to a function, all but the first dimension must be specified.
- Row-major layout:
a[i][j]
is contiguous in thej
direction; cache-friendliness depends on traversal order. - Very large arrays on the stack can overflow; prefer static or dynamic allocation.
- Variable-length arrays (VLAs) require care with dimensions and may not be supported by all compilers.
Exercises
- Write a function to add two 2x3 matrices and print the result.
- Search for a value in a 2D array and return its coordinates.