灵活数组成员在C ++中是否有效?

在C99中,您可以这样声明结构的灵活数组成员:


struct blah

{

    int foo[];

};

但是,当某人在工作时尝试使用C ++中的clang编译一些代码时,该语法不起作用。(它已经与MSVC一起使用。)我们必须将其转换为:


struct blah

{

    int foo[0];

};

纵观C ++标准,我发现根本没有引用弹性成员数组。我一直认为这[0]是一个无效的声明,但是显然对于灵活的成员数组而言,它是有效的。弹性成员数组在C ++中实际上有效吗?如果是这样,是正确的声明[]还是[0]?


繁花如伊
浏览 506回答 3
3回答

犯罪嫌疑人X

C ++于1998年首次标准化,因此它早于C中添加了灵活数组成员(C99中的新增功能)。2003年对C ++进行了更正,但是并没有添加任何相关的新功能。C ++的下一个修订版(C ++ 0x)仍在开发中,似乎没有在其中添加灵活的数组成员。

跃然一笑

C ++在结构的末尾不支持C99灵活数组成员,无论是使用空索引符号还是0索引符号(除非特定于供应商的扩展名):struct blah{&nbsp; &nbsp; int count;&nbsp; &nbsp; int foo[];&nbsp; // not valid C++};struct blah{&nbsp; &nbsp; int count;&nbsp; &nbsp; int foo[0]; // also not valid C++};据我所知,C ++ 0x也不会添加它。但是,如果将数组的大小设置为1个元素:struct blah{&nbsp; &nbsp; int count;&nbsp; &nbsp; int foo[1];};事情是有效的,并且运作良好。您可以使用不太可能出现一次性错误的表达式分配适当的内存:struct blah* p = (struct blah*) malloc( offsetof(struct blah, foo[desired_number_of_elements]);if (p) {&nbsp; &nbsp; p->count = desired_number_of_elements;&nbsp; &nbsp; // initialize your p->foo[] array however appropriate - it has `count`&nbsp; &nbsp; // elements (indexable from 0 to count-1)}因此,它可以在C90,C99和C ++之间移植,并且与C99的灵活数组成员一样好用。雷蒙德·陈(Raymond Chen)对此写得很好:为什么有些结构以大小为1的数组结尾?注意:在Raymond Chen的文章中,在初始化“灵活”数组的示例中有一个错字/错误。它应显示为:for (DWORD Index = 0; Index < NumberOfGroups; Index++) { // note: used '<' , not '='&nbsp; TokenGroups->Groups[Index] = ...;}

慕码人8056858

第二个将不包含元素,而是指向blah。因此,如果您具有这样的结构:struct something{&nbsp; int a, b;&nbsp; int c[0];};您可以执行以下操作:struct something *val = (struct something *)malloc(sizeof(struct something) + 5 * sizeof(int));val->a = 1;val->b = 2;val->c[0] = 3;在这种情况下,c它将表现为5 ints 的数组,但数组中的数据将在something结构之后。我正在研究的产品将其用作大小字符串:struct String{&nbsp; unsigned int allocated;&nbsp; unsigned int size;&nbsp; char data[0];};由于受支持的体系结构,这将消耗8个字节plus allocated。当然,所有这些都是C,但是例如g ++毫不费力地接受了它。
打开App,查看更多内容
随时随地看视频慕课网APP