简体   繁体   中英

Constant size array initalization with sizeof

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]

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));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM