简体   繁体   English

使用sizeof的恒定大小数组初始化

[英]Constant size array initalization with sizeof

Why does the following work just fine with gcc c99 为什么以下工作在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. n是一个不同于sizeof a / sizeof *a的变量,因为后者是在编译时计算的。

int b[n] declares a variable length array. int b[n]声明一个可变长度的数组。 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 . 您可以使用循环或memeset函数将其所有元素初始化为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. 第一个示例起作用是因为sizeof a / sizeof *a是一个常量表达式,可以用作数组维。

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. 在第二个示例中, n不是常量表达式,因此编译器将b视为可变长度数组的定义,错误是说VLA可能未初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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