I am reading this to consider about how to dynamically allocate memory for a two-dimensional array.
I notice that a variable value cols
can be used as size to define int (*arr)[cols]
, as C
language has variable-length arrays(VLA) feature, then I try modifying the code into C++
like:
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
void* allocate(size_t rows, size_t cols)
{
int (*arr)[cols] = (int (*)[cols])malloc(rows *sizeof(*arr));
memset(arr, 0, rows *sizeof(*arr));
return arr;
}
int main() {
size_t rows, cols;
scanf("%zu %zu", &rows, &cols);
int (*arr)[cols] = (int (*)[cols])allocate(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%3d", arr[i][j]);
}
printf("\n");
}
}
compile with gcc 11.2 -std=c++11
To my surprise, this works well and compiler does not report any warning. AFAIK C++
has no VLA feature, I used to think this code should be forbidden. So why could this work?