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

标签 c arrays global-variables

为什么数组 a 没有被全局变量 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 初始化。

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

最佳答案

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

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

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

大概您不希望 a 具有可变长度,因此您需要的是:

#define size 5

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

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 的情况下“应该”发生什么。为可变长度数组指定固定大小的初始值并没有真正意义。

关于c - 为什么我不能创建一个大小由全局变量决定的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2427336/

相关文章:

c - “while(*s++ = *t++)” 和 malloc

c - c 指针段错误

c - 值不是数组、指针或 vector

c - 在 C 中初始化 struct 中的 int 数组

c++ - 创建一个固定大小的 std::vector 并写入元素

c# - 比较 .NET 中的两个字节数组

python - (Python) 我应该使用参数还是使其成为全局参数?

c - 为什么 "const extern"报错?

javascript - 将数字转换为反转的数字数组

javascript - 具有 ID 的 DOM 树元素是否成为全局属性?