gpt4 book ai didi

c++ - 数组初始化 [c/c++]

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:59:55 32 4
gpt4 key购买 nike

为什么不允许这样做?

#include <cstdio>

struct Foo {
int fooId;
char arr[ ];
} fooList[] =
{ {1, {'a', 'b'}},
{2, {'c', 'd'}}
};

int main()
{
for (int i = 0; i < 2; i++)
printf("%d %c\n", fooList[i].fooId, fooList[i].arr[0]);
}

然而,这是允许的:

struct Foo {
int fooId;
char arr[2]; // this line modified
} fooList[] =
{ {1, {'a', 'b'}},
{2, {'c', 'd'}}
};

最佳答案

只有 C 结构的 last 成员可以像 arr[] 那样灵活。

无耻地抄袭 ISO C99 标准第 6.7.2.1 段第 16 段:

16 As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. With two exceptions, the flexible array member is ignored. First, the size of the structure shall be equal to the offset of the last element of an otherwise identical structure that replaces the flexible array member with an array of unspecified length.106)...

编辑:

关于 C++,参见 this .底线:C++ 中根本不允许使用灵活的数组成员 - 至少目前是这样。

关于c++ - 数组初始化 [c/c++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4862914/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com