简体   繁体   English

使用灵活的数组成员分配struct

[英]Allocating struct with flexible array member

This is C99 code: 这是C99代码:

typedef struct expr_t
{
    int n_children; 
    foo data; // Maybe whatever type with unknown alignment
    struct expr_t *children[];
} expr_t;

Now, how do I allocate memory ? 现在,我该如何分配内存?

expr_t *e = malloc (sizeof (expr_t) + n * sizeof (expr_t *));

or 要么

expr_t *e = malloc (offsetof (expr_t, children) + n * sizeof (expr_t *));

?

Is sizeof even guaranteed to work on an type with flexible array member (GCC accepts it) ? sizeof甚至可以保证在具有灵活阵列成员的类型上工作(GCC接受它)吗?

expr_t *e = malloc (sizeof (expr_t) + n * sizeof (expr_t *)); is well defined in C99. 在C99中有明确的定义。 From the C99 specification 6.7.2.1.16: 根据C99规范6.7.2.1.16:

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. 这被称为灵活的阵列成员。 In most situations, the flexible array member is ignored. 在大多数情况下,将忽略灵活数组成员。 In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply. 特别地,结构的尺寸好像省略了柔性阵列构件,除了它可以具有比省略意味着更多的拖尾填充。

If the compiler accepts the declaration of a struct with a flexible array member, the sizeof operator for that struct should yield the size of the struct as if the flexible array member doesn't exist. 如果编译器接受具有灵活数组成员的结构的声明,则该结构的sizeof运算符应该产生结构的大小,就好像灵活数组成员不存在一样。

The correct allocation of such a struct would be: 这种结构的正确分配是:

expr_t *e = malloc (sizeof(expr_t) + n * sizeof(struct expr_t *));

You can still do this trick even if flexible array members are not supported by the compiler. 即使编译器不支持灵活的数组成员,您仍然可以执行此操作。 Just declare the array member of your struct as having a size of 1 , and then allocate n - 1 items instead of n . 只需将结构的数组成员声明为大小为1 ,然后分配n - 1项而不是n

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

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