0 day streak
c / intermediate
Snippet

Multi-dimensional Variable Length Arrays

Variable Length Arrays (VLA) allow function parameters to specify dimensions that are determined at runtime. This makes passing multi-dimensional arrays much cleaner than using manual pointer arithmetic or flattened arrays.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
void fill_matrix(int rows, int cols, int matrix[rows][cols]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = i * cols + j;
}
}
}
int main() {
int r = 3, c = 4;
int my_matrix[r][c];
fill_matrix(r, c, my_matrix);
printf("Element [2][3]: %d\n", my_matrix[2][3]);
return 0;
}
Breakdown
1
int matrix[rows][cols]
The compiler uses the 'rows' and 'cols' parameters to calculate correct offsets for the 2D array.
2
int my_matrix[r][c];
Allocates the array on the stack with dimensions specified by variables r and c.