在C变量长度数组和到位初始化它 [英] variable length arrays in C and initializing it in place

查看:127
本文介绍了在C变量长度数组和到位初始化它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C99可定义阵列与非恒定尺寸,即用于定义一个阵列可以在运行时改变其尺寸。 code片段来解释它是,

C99 allows defining arrays with non-constant size, i.e. the size used to define an array can change on runtime. Code snippet to explain it would be,

void dummy_function1(unsigned int length) {

 char arrA[length];  //Allowed
 .
 .
}

然而,它不允许进行初始化的地方,即

However, it does not allow initializing it in place, i.e.

void dummy_function2(unsigned int length) {

 char arrA[length]={0}; //Not Allowed, compiler throws an error
 char arrB[10]={0};     //Allowed
 .
}

我不明白,为什么这种行为差异数组是可变长度,其中一个是固定长度。在这两种情况下,在调用功能时的阵列将被给定的存储器

I do not understand, why is this difference in behavior for array which is variable length and the one which is constant length. In both cases, the array would be given memory when the function is invoked.

推荐答案

它看起来像这样不被标准所允许的,如果我们看一下C99标准草案 6.7.8 初始化的段落的 3 的说(重点煤矿):

It looks like this is not allowed by the standard if we look at the C99 draft standard section 6.7.8 Initialization paragraph 3 says(emphasis mine):

要初始化的实体的类型应为未知大小的数组或对象类型
  该不是一个可变长度的数组类型

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.

至于为何很可能是因为支持可变长度数组初始化,需要在运行时的工作不确定数量。

As to why most likely because supporting initialization of a variable length array would require indeterminate amount of work at run-time.

这篇关于在C变量长度数组和到位初始化它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆