c / intermediate
Snippet
Passing Multidimensional Arrays to Functions
In C, multidimensional arrays are stored in row-major order. To correctly calculate memory offsets, a function receiving a 2D array must know the size of the columns (the second dimension), while the number of rows can be passed as a separate argument.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>#define COLS 3// When passing a 2D array, all dimensions except the first must be specifiedvoid print_grid(int grid[][COLS], int rows) {for (int i = 0; i < rows; i++) {for (int j = 0; j < COLS; j++) {printf("%d ", grid[i][j]);}printf("\n");}}int main() {int matrix[2][COLS] = {{1, 2, 3},{4, 5, 6}};print_grid(matrix, 2);return 0;}
Breakdown
1
int grid[][COLS]
Specifies that the function accepts an array where each element is an array of COLS integers.
2
grid[i][j]
Accesses the element by calculating the offset: base_address + (i * COLS + j) * sizeof(int).