struct 中这个 data[0] 声明的目的是什么?
What is the purpose of this `data[0]` declaration in struct?
在 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]
在这里做什么?
在 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(强调我的):
Zero-length arrays are allowed in GNU C
请注意 "GNU C"(C 的 GCC 实现)在 ISO C 之上有自己的扩展。
在 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]
在这里做什么?
在 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(强调我的):
Zero-length arrays are allowed in GNU C
请注意 "GNU C"(C 的 GCC 实现)在 ISO C 之上有自己的扩展。