【问题标题】:What is the purpose of this `data[0]` declaration in struct? [duplicate]这个 `data[0]` 在 struct 中声明的目的是什么? [复制]
【发布时间】:2017-11-18 06:37:00
【问题描述】:

在C中,灵活数组成员的语法如下:

struct s 
{ 
    int n; 
    double d[];  // flexible array member
};

而且,零大小数组在 C 中是非法的。

如果我这样声明数组:

struct s 
{ 
    double d[0];  // Zero size array
};

GCC 给出警告:

warning: ISO C forbids zero-size array 'd' [-Wpedantic]

所以,我要回答我的主要问题。

我看到了下面的代码here。

struct squashfs_xattr_entry {
    __le16          type;
    __le16          size;
    char            data[0];
};

在 C 中的零大小数组是非法的。

那么,

  • data[0] 在结构中声明的目的是什么?
  • data[0] 在这里做什么?

【问题讨论】:

  • @chux 特别是 GNU GCC 和 Clang。然而,M$VC 拒绝零长度数组。
  • 所以你甚至没有在谷歌上搜索过有多少个重复项?!

标签: c arrays structure c99


【解决方案1】:

在 C99(1999 年发布的 C 的 ISO 标准版本)之前,实现灵活数组成员的唯一方法是编译器是否支持它作为扩展。 GCC 通过使用0 的静态长度来支持它,因此是foo buffer[0]。

C99 使其合法,但他们决定规定语法 foo buffer[] 而不是保留 GCC 的 [0] 版本。

GCC 仍然支持 buffer[0] 以与 C99 之前编写的代码兼容。

这在 GCC 的文档中有解释:https://gcc.gnu.org/onlinedocs/gcc-4.4.4/gcc/Zero-Length.html(强调我的):

零长度数组在 GNU C 中是允许的

请注意,“GNU C”(C 的 GCC 实现)在 ISO C 之上有自己的扩展。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-07-12
  • 1970-01-01
  • 2012-07-13
  • 1970-01-01
  • 2011-04-08
  • 2017-01-27
  • 2019-10-23
  • 1970-01-01
相关资源
最近更新 更多