我在联合中声明了一个灵活的数组成员,如下所示:
#include <stdio.h>
union ut
{
int i;
int a[]; // flexible array member
};
int main(void)
{
union ut s;
return 0;
}
和编译器给出一个错误:
source_file.c:8:9: error: flexible array member in union
int a[];
但是,声明的数组 zero 大小如下:
union ut
{
int i;
int a[0]; // Zero length array
};
它工作正常 .
Why does zero length array work fine union?
2 回答
int a[]
是C标准符号(自C99起) .int a[0]
是GNU C语法,它早于C99 . 其他编译器也可能支持它,我不知道 .您的编译器似乎默认使用GNU扩展的C90标准,这就是后者编译的原因,但首先是编译器 .
此外,如Lundin's answer中所述,标准C根本不支持
union
中的灵活数组成员 .尝试将
-std=c99
或-std=c11
添加到编译器选项(gcc docs here) .此外
-pedantic
或-pedantic-errors
也可能是个好主意,它会强制执行更严格的标准合规性 .而且,除了强制性,
-Wall -Werror
也不会伤害......不,工会不支持灵活的阵列成员,只支持结构 . C116.7.2.1§18
此外,零长度数组无效C,这是gcc非标准扩展 . 之所以能够使用它是因为你的编译器gcc被配置为编译"non-standard GNU language"的代码 . 如果您希望编译C编程语言的代码,则需要添加编译器选项
-std=c11 -pedantic-errors
.