Reputation: 6870
Why does the following work just fine with gcc c99
int a[] = {1,2,3};
int b[sizeof a / sizeof *a] = {0};
But this gives compilation errors
int n = sizeof a / sizeof *a;
int b[n] = {0};
Error
file.c:14:2: error: variable-sized object may not be initialized
file.c:14:2: warning: excess elements in array initializer [enabled by default]
file.c:14:2: warning: (near initialization for 'b') [enabled by default]
Upvotes: 1
Views: 86
Reputation: 106092
n
is a variable unlike sizeof a / sizeof *a
because latter is calculate at compile time.
int b[n]
declares a variable length array. You can't initialize it by using initializer list. You can use a loop or memeset
function to initialize all of its elements to 0
.
memset(b, 0, sizeof(b));
Upvotes: 3
Reputation: 122443
The first example works because sizeof a / sizeof *a
is a constant expression, and it's OK to be used as array dimension.
In the second example, n
is NOT a constant expression, so the compiler treats b
as a definition of variable length array, the error is saying VLAs may not be initialized.
Upvotes: 3