"structure with flexible array member shall not be a member of a structure"的理由是什么?

What is the rationale for "structure with flexible array member shall not be a member of a structure"?

C11,6.7.2.1 结构和联合说明符,约束,3(添加了强调):

A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.

C 的基本原理,修订版 5.10,2003 年 4 月(强调已添加):

Similarly, structures containing flexible arrays can’t occur in other structures or in arrays.

因此,C 的基本原理没有提供基本原理。原理是什么?

具有灵活数组成员的结构只有在动态分配的情况下才能真正正确使用。例如:

struct s1 {
    int a;
    int b;
    int c[];
};
...
struct s1 *x = malloc(sizeof(struct s1) + 5 * sizeof(int));

让我们假设典型的结构填充和 sizeof(int)==4。这将使 sizeof(struct s1)==8.

现在想象一下,如果这样的结构是另一个结构的成员:

struct s2 {
    int a;
    struct s1 b;
    int c;
};

struct s2b 成员将从偏移量 4 开始。但是 c 成员呢?鉴于 sizeof(struct s1)==8,这将使成员 c 具有偏移量 12。但是 b 成员无法为其包含 [=17] 预留任何 space =] 成员.

因为给定结构成员的偏移量是在编译时设置的,所以无法为 struct s1 内部的灵活数组成员 c 分配 space。

理论上,如果具有灵活数组成员的结构是最后一个成员:

struct s2 {
    int a;
    int b;
    struct s1 c;
};

那么它 可以 工作,但是这意味着 struct s2 也遵循与具有灵活数组成员的结构相同的规则,从而导致级联效应.这将使确定哪些结构受此规则约束变得更加困难。

因此,不允许将具有灵活数组成员的结构作为另一个结构或数组的成员。