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.9p22和 6.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/