我在 union 中声明了一个灵活的数组成员,像这样:
#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[];
但是,像这样声明数组零大小:
union ut
{
int i;
int a[0]; // Zero length array
};
而且它工作正常。
为什么零长度数组可以很好地 union 工作?
最佳答案
不, union 不支持灵活的数组成员,只支持结构。 C11 6.7.2.1 §18
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.
此外,零长度数组不是有效的 C,那是 gcc 的非标准扩展。你让它工作的原因是因为你的编译器 gcc 配置为编译“非标准 GNU 语言”的代码。如果您希望它为 C 编程语言编译代码,则需要添加编译器选项 -std=c11 -pedantic-errors
。
关于c - union 是否支持灵活的数组成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46233400/