The malloc’ed VLA
23, Nov, 2017Many times, I heard that variable length arrays in C are evil. “Because, they are allocated on stack.” Oh, really?
int n = foo(); int m = bar(); float (*arr)[m] = malloc(sizeof(float) * n * m);
This is THE simplest way for dynamically allocated n-dimensional arrays in C! No more index calculation, simply:
for (int i = 0, k = 0; i < n; i++) {
for (int j = 0; j < m; j++, k++) {
arr[i][j] = k;
}
}
- Posted by michal in
- Add a comment