用 sizeof 初始化常量数组

标签 c arrays

为什么下面的代码在 gcc c99 上工作得很好

int a[] = {1,2,3};
int b[sizeof a / sizeof *a] = {0};

但这会产生编译错误

int n = sizeof a / sizeof *a;
int b[n] = {0};

错误

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]

最佳答案

第一个例子是可行的,因为sizeof a/sizeof *a是一个常量表达式,可以用作数组维度。

在第二个例子中,n 不是常量表达式,因此编译器将 b 视为可变长度数组的定义,错误是说 VLAs 可能不是初始化。

关于用 sizeof 初始化常量数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28500988/

相关文章:

c - 如何消除相当大的对话框上的闪烁?

c++ - Win32 API 定时器

c - 用 write() 函数写入 Unicode

python - numpy中的随机单热矩阵

php - 仅当值在 PHP 循环期间在特定组内时才打印出某些内容

python - 如何用另一个数组中的值填充两个 numpy 数组

c - 以最优方法在链表中找到最小值

c - 如何计算数组中相似数字的数量

php - 在 foreach 循环中循环的数组中添加项目

javascript - 从复选框数组中插入多个值,并以逗号分隔