c - 没有明确长度的 sizeof 数组

标签 c arrays sizeof

sizeof 是否可以安全地用于已声明但未在方括号内指定显式大小但已在声明中初始化的数组?

考虑以下代码:

unsigned int arr[] = { 1, 2, 3 };
size_t bytes = sizeof arr;

如果在没有任何特殊编译器标志的情况下使用 clang-800.0.42.1 在 macOS 上编译,这会产生 12 的预期结果。
但是 C 标准(或任何 C 标准,如果它们在这方面不同)是否保证这种情况?或者我是否必须像 unsigned int arr[3] 那样声明它才能使其“正常”?

最佳答案

是的,如果没有指定大小,标准保证数组元素计数将等于数组初始值设定项中的元素数。看 C11 standard draft 6.7.9p226.7.9p25 :

If an array of unknown size is initialized, its size is determined by the largest indexed element with an explicit initializer. The array type is completed at the end of its initializer list.

EXAMPLE 2 The declaration

int x[] = { 1, 3, 5 };

defines and initializes x as a one-dimensional array object that has three elements, as no size was specified and there are three initializers.

关于c - 没有明确长度的 sizeof 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41511729/

相关文章:

c - 我需要从 C 中的 .txt 文件读取 x 和 y 值

c - 移动数组的列

c - 如何根据文件unistd_64.h或unistd_32.h中的编号输出系统调用的名称?

php - 如何从数据库循环中获取值并将它们相加以备后用

c++ - 如何在循环中获取数组的大小

c - C中的外部数组没有大小

c - Chromium OS 是用什么语言编写的?

python - 从python中的二维数组中随机采样子数组

javascript - 按 parentId javascript 对平面数组进行排序

c++ - sizeof(size_t) 可以小于 sizeof(int) 吗?