简体   繁体   English

在另一个结构中具有灵活数组成员的结构

[英]a struct with a flexible array member in another struct

Is something like the code below valid? 以下代码有效吗?

struct foo {
    int a;
    int b[];
};

struct bar {
    int c;
    struct foo d;
};

struct bar *x = malloc(sizeof(struct bar) + sizeof(int [128]));

It seems ok to me, but I am a bit skeptical because compiler does not complain if I do: 对我来说似乎没问题,但我有点怀疑,因为如果我这样做,编译器不会抱怨:

struct bar {
    struct foo d;
    int c;
};

It's not okay. 这不好。 Section 6.7.2.1 (in n1570), point 3 says 第6.7.2.1节(在1570年),第3点说

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; 3结构或联合不应包含具有不完整或函数类型的成员(因此,结构不应包含其自身的实例,但可包含指向其自身实例的指针),除了具有更多结构的结构的最后一个成员一个命名成员可能有不完整的数组类型; 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. 这样的结构(以及可能递归地包含这种结构的成员的任何联合)不应是结构的成员或数组的元素。

So a struct with a flexible array member may not be part of another struct. 因此,具有灵活数组成员的struct可能不是另一个结构的一部分。

(It may well work as the last member of a struct, though, if the compiler accepts it.) (但是,如果编译器接受它,它可能作为结构的最后一个成员。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM