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("=", 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?
CodePudding user response:
-std=c 11
doesn't mean "compile strictly according to C 11" but "enable C 11 features." Just as -std=gnu 11
(the default setting) means enable gnu 11 features, which is a superset of C 11.
To get strictly compliant behavior, you must use -std=c 11 -pedantic-errors
. And then you get this:
error: ISO C forbids variable length array 'arr' [-Wvla]
See What compiler options are recommended for beginners learning C? for details. It was written for C but applies identically to g as well.