0 Tage Serie
c / intermediate
Snippet

Mehrdimensionale Variable-Length-Arrays

Variable-Length-Arrays (VLA) erlauben es Funktionsparametern, Dimensionen anzugeben, die zur Laufzeit bestimmt werden. Dies macht das Übergeben mehrdimensionaler Arrays deutlich sauberer als manuelle Pointer-Arithmetik.

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;
}
Erklärung
1
int matrix[rows][cols]
Der Compiler nutzt die Parameter 'rows' und 'cols', um die korrekten Offsets für das 2D-Array zu berechnen.
2
int my_matrix[r][c];
Allokiert das Array auf dem Stack mit Dimensionen, die durch die Variablen r und c definiert sind.