c - 将动态大小的可变长度数组 (VLA) 初始化为 0

标签 c arrays gcc initialization variable-length

下面这行代码,在栈上创建了一个变长数组:

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)中的一个约束:

  1. 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/

相关文章:

c - '->' doesnt doesn' t 适用于结构内部的结构

C:我的反向字符串函数有什么问题?

javascript - 根据 DOM 元素中数据字段的值创建数组

c - 堆栈与堆溢出检测

c - 如何在C中获取时间值作为引用参数

c - 错误 : expected ';' , ',' 或 ')' token 之前的 '&'|在网上找到的一个简单的 C 程序

c - 变量超出范围并且内存保留值

python - 从某个索引开始迭代列表

c - 如何防止使用 arm-none-eabi-gcc 编译器对该函数进行 vector 运算优化?

c++ - 静态成员显式定义