如何将匿名VLA分配给指针?

问题描述 投票:0回答:1

目前我正在将 VLA 分配给指针,如下所示

struct Foo {
    int* array;
};

int array[size];

struct Foo foo = {
    .array = array;
};

是否可以用“匿名”数组替换它?

我尝试过的:

struct Foo foo = {
    .array = (int[size]) {} // fatal error: variable-sized object may not be initialized
};

我所希望的:

struct Foo foo = {
    .array = int[size]; // something similar to this if I am making any sense.
};

PS:我不是在寻找动态内存分配(malloc/calloc)。

c pointers variable-length-array anonymous-objects
1个回答
0
投票

是否可以用“匿名”数组替换它?

没有。

具体来说,您询问如何创建匿名可变长度数组。 C 标准不允许这些。

对于复合文字 (

(){}
),C 标准规定:

C17 §6.5.2.5 ¶1 类型名称应指定完整的对象类型或未知大小的数组,但不能指定变长数组类型

© www.soinside.com 2019 - 2024. All rights reserved.