在C中声明一个变长数组作为全局变量 [英] declaring a variable-length array as a global variable in C

查看:271
本文介绍了在C中声明一个变长数组作为全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将变长数组声明为全局变量?

在扫描长度之前在函数中声明可变长度数组时,它会编译但不会运行。它给分段错误。当相同的声明语句被移到扫描语句之下时,它运行正常。



如果我们想要一个全局变量长度的数组可用于所有函数,我们怎么做到这一点?这里的问题是数组的长度只能通过一些函数进行扫描。

解决方案

你不能那样做。
这是标准草案的内容:


6.7.6.2数组声明符



2如果一个标识符被声明为具有可变的修饰类型,那么
应该是一个普通的标识符(如6.2.3所定义的),没有
链接,并具有块范围或函数原型范围。如果
标识符被声明为一个静态或线程为
的存储持续时间的对象,则它不应具有可变长度数组类型。


另外,


10示例4可变修改(VM)类型的所有声明都必须位于任一块范围或
函数的原型范围。使用_Thread_local,static或extern
存储类说明符声明的数组对象不能具有可变长度数组(VLA)类型。但是,用
声明静态存储类说明符的对象可以具有VM类型(即指向VLA类型的指针)。最后,所有用VM类型声明的
标识符都必须是普通标识符,因此不能是
结构或联合体的成员。



How is it possible to declare a variable-length array as a global variable ?

when variable length array is declared in a function before the length is scanned, it compiles but does not run. it gives segmentation fault. when the same declaration statement is shifted below the scanning statement, it runs fine.

in case we want a variable length array globally available to all functions, how can we do that? problem here is the that the length of the array can only be scanned through some function only.

解决方案

You can't do that. Here's what the draft of the standard says:

6.7.6.2 Array declarators

2 If an identifier is declared as having a variably modified type, it shall be an ordinary identifier (as defined in 6.2.3), have no linkage, and have either block scope or function prototype scope. If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.

Also,

10 EXAMPLE 4 All declarations of variably modified (VM) types have to be at either block scope or function prototype scope. Array objects declared with the _Thread_local, static, or extern storage-class specifier cannot have a variable length array (VLA) type. However, an object declared with the static storage-class specifier can have a VM type (that is, a pointer to a VLA type). Finally, all identifiers declared with a VM type have to be ordinary identifiers and cannot, therefore, be members of structures or unions.

这篇关于在C中声明一个变长数组作为全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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