为什么我不能创建一个大小由全局变量决定的数组? [英] Why can't I create an array with size determined by a global variable?

查看:27
本文介绍了为什么我不能创建一个大小由全局变量决定的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么数组 a 没有被全局变量 size 初始化?

Why does the array a not get initialized by global variable size?

#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

据我所知,数组应该由 size 初始化.

According to me, the array should get initialized by size.

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

And what would be the answer if I insist on using global variable (if it is possible)?

推荐答案

In C99, 6.7.8/3:

In 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:

一个整数常量表达式应具有整数类型且仅应有整数操作数常量,枚举常量,字符常量,sizeof结果为整数的表达式常量和浮动常量是强制转换的直接操作数.

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 具有变长数组类型,因为 size 不是整数常量表达式.因此,它不能有初始化列表.

a has variable length array type, because size is not an integer constant expression. Thus, it cannot have an initializer list.

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

In C90, there are no VLAs, so the code is illegal for that reason.

在 C++ 中也没有 VLA,但您可以将 size 设为 const int.那是因为在 C++ 中,您可以在 ICE 中使用 const int 变量.在 C 中你不能.

In C++ there are also no VLAs, but you could make size a const int. That's because in C++ you can use const int variables in ICEs. In C you can't.

大概你不打算 a 有可变长度,所以你需要的是:

Presumably you didn't intend a to have variable length, so what you need is:

#define size 5

如果您确实希望 a 具有可变长度,我想您可以这样做:

If you actually did intend a to have variable length, I suppose you could do something like this:

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

或者也许:

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

不过,很难说在 size != 5 的情况下应该"发生什么.为可变长度数组指定固定大小的初始值实际上没有意义.

It's difficult to say, though, what "should" happen here in the case where size != 5. It doesn't really make sense to specify a fixed-size initial value for a variable-length array.

这篇关于为什么我不能创建一个大小由全局变量决定的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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