下面这行代码,在栈上创建了一个变长数组:
char name[length] = {'\0'};
生成以下编译器诊断信息:
error: variable-sized object may not be initialized
warning: excess elements in array initializer
warning: (near initialization for ‘name’)
我可以使用哪些选项来初始化 VLA?我是否被迫使用如下一行:
memset(name, 0, sizeof(name));
代替?
最佳答案
是的,您必须为 VLA 的初始化编写代码(可以是您所描述的 memset()
,或者您喜欢的任何其他方式)。
它只是 C 标准(§6.7.8)中的一个约束:
- The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.
关于c - 将动态大小的可变长度数组 (VLA) 初始化为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4393779/