为什么我不能创建一个由全局变量确定的大小的数组?

为什么数组没有被全局变量大小初始化?
#include<stdio.h>

int size = 5;

int main()
{
    int a[size] = {1,2,3,4,5};
    printf("%d",a[0]);

    return 0;
}

编译错误显示

variable-sized object may not be initialized

据我说,数组应该被大小初始化.

如果我坚持使用全局变量(如果有可能的话)会是什么答案?

解决方法

在C99中,6.7.8 / 3:

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.

6.6 / 2:

A constant expression can be evaluated
during translation rather than runtime

6.6 / 6:

An integer constant expression
shall have integer type and shall only
have operands that are integer
constants,enumeration constants,
character constants,sizeof
expressions whose results are integer
constants,and floating constants that
are the immediate operands of casts.

6.7.5.2/4:

If the size is an integer constant
expression and the element type has a
kNown constant size,the array type is
not a variable length array type;
otherwise,the array type is a
variable length array type.

a具有可变长度数组类型,因为大小不是整数常量表达式.因此,它不能有一个初始化器列表.

在C90中,没有VLA,因此代码是非法的.

在C中也没有VLA,但你可以使大小为const int.这是因为在C中,可以在ICE中使用const int变量.在C你不能.

大概你并不打算改变长度,所以你需要的是:

#define size 5

如果你真的想要一个可变长度,我想你可以这样做:

int a[size];
int initlen = size;
if (initlen > 5) initlen = 5;
memcpy(a,(int[]){1,5},initlen*sizeof(int));

或者可能:

int a[size];
for (int i = 0; i < size && i < 5; ++i) {
    a[i] = i+1;
}

很难说,在size!= 5的情况下,“应该”会发生什么.对可变长度的数组指定一个固定大小的初始值是没有意义的.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...