初始化一个动态大小的可变长度数组(VLA)到0。

时间:2022-09-25 21:41:11

The following line of code, which creates a variable-length array on the stack:

以下代码行,在堆栈上创建一个可变长度数组:

char name[length] = {'\0'};

Generates the following compiler diagnostics:

生成以下编译器诊断:

error: variable-sized object may not be initializedwarning: excess elements in array initializerwarning: (near initialization for ‘name’)

What options are available to me for initializing VLAs? Am I forced to use a line such as:

对于初始化VLAs,我有什么选择?我是否*使用这样的句子:

memset(name, 0, sizeof(name));

Instead?

而不是?

1 个解决方案

#1


5  

Yes, you must write code for the initialisation of VLAs (which could be a memset() like you have described, or any other way that you care to).

是的,您必须为VLAs的初始化编写代码(可以是如您所描述的memset(),或者您关心的任何其他方式)。

It is simply a constraint in the C standard (§6.7.8):

它只是一个约束在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.
  2. 要初始化的实体的类型应该是未知大小的数组,或者不是可变长度数组类型的对象类型。

#1


5  

Yes, you must write code for the initialisation of VLAs (which could be a memset() like you have described, or any other way that you care to).

是的,您必须为VLAs的初始化编写代码(可以是如您所描述的memset(),或者您关心的任何其他方式)。

It is simply a constraint in the C standard (§6.7.8):

它只是一个约束在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.
  2. 要初始化的实体的类型应该是未知大小的数组,或者不是可变长度数组类型的对象类型。