c - union 是否支持灵活的数组成员?

标签 c c99 unions flexible-array-member

我在 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/

相关文章:

android - 在 windows 上构建 .so 库以供在 android 上使用

c - C 中标识符的命名空间

c - 从 double 到 float 的转换是否总是潜在地调用未定义的行为?

c - 使用 scanf 获取小数

c++ - C++ union 的性能影响

c++ - 如果我们只有一个成员,结构和 union 之间有什么区别吗?

c++ - 使 vector 3D 从 vector AND 派生,需要保留字段 x y z

c - 如何在 C (unix) 中读取 mp3 文件标签?

c - fgets();这部分代码是如何工作的? C语言编程

C 编程 - 分析字符串中的散文?