可变长度数组是否以 C 中的默认 0 值开头?
Do variable length arrays start with default 0 values in C?
我知道我 cannot initialize variable-length arrays 在 C 中有明确提供的值。 不支持以下代码:
void main() {
int l = 2;
float test[l] = {1.0, 2.0}; // my compiler says: "Variable-sized object may not be initialized"
}
我的问题是:如果我不尝试给出任何值:
void main() {
int l = 2;
float test[l];
}
…C 编译器会确保它默认初始化为零吗?
很高兴接受有据可查的答案,但根据经验,答案是否:内存不是零初始化。
以下代码的变体经常(但不总是!)中止:
int main() {
int l = 99;
float test[l];
assert(test[0] == 0.0);
assert(test[42] == 0.0);
return 0;
}
所以除非我确定要初始化每个成员,否则有必要自己将其设置为已知状态,例如
int main() {
int l = 99;
float test[l];
memset(test, 0, sizeof test);
// …now the array content is in a known state…
}
我相信 C++ behaves differently 这可能是我所记得的。
变长数组默认不初始化,也不能显式初始化,除了calloc
等内存分配例程可能会初始化space。
C 2018 6.7.6.2(“数组声明符”)2 说:
… If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.
因此可变长度数组的存储持续时间必须是其他存储持续时间之一:自动或分配[6.2.4 1]。 (有一个临时存储持续时间,但仅适用于结构或联合[6.2.4 7]。)
6.7.9 10表示默认不初始化自动存储时长的对象:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate…
此外,6.7.9 3 表示您不能显式初始化可变长度数组:
The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.
我知道我 cannot initialize variable-length arrays 在 C 中有明确提供的值。 不支持以下代码:
void main() {
int l = 2;
float test[l] = {1.0, 2.0}; // my compiler says: "Variable-sized object may not be initialized"
}
我的问题是:如果我不尝试给出任何值:
void main() {
int l = 2;
float test[l];
}
…C 编译器会确保它默认初始化为零吗?
很高兴接受有据可查的答案,但根据经验,答案是否:内存不是零初始化。
以下代码的变体经常(但不总是!)中止:
int main() {
int l = 99;
float test[l];
assert(test[0] == 0.0);
assert(test[42] == 0.0);
return 0;
}
所以除非我确定要初始化每个成员,否则有必要自己将其设置为已知状态,例如
int main() {
int l = 99;
float test[l];
memset(test, 0, sizeof test);
// …now the array content is in a known state…
}
我相信 C++ behaves differently 这可能是我所记得的。
变长数组默认不初始化,也不能显式初始化,除了calloc
等内存分配例程可能会初始化space。
C 2018 6.7.6.2(“数组声明符”)2 说:
… If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.
因此可变长度数组的存储持续时间必须是其他存储持续时间之一:自动或分配[6.2.4 1]。 (有一个临时存储持续时间,但仅适用于结构或联合[6.2.4 7]。)
6.7.9 10表示默认不初始化自动存储时长的对象:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate…
此外,6.7.9 3 表示您不能显式初始化可变长度数组:
The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.