微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

为什么数组没有被全局变量大小初始化?
#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的情况下,“应该”会发生什么.对可变长度的数组指定一个固定大小的初始值是没有意义的.

原文地址:https://www.jb51.cc/c/112005.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐