【发布时间】:2012-09-22 18:07:12
【问题描述】:
这是 C99 代码:
typedef struct expr_t
{
int n_children;
foo data; // Maybe whatever type with unknown alignment
struct expr_t *children[];
} expr_t;
现在,我该如何分配内存?
expr_t *e = malloc (sizeof (expr_t) + n * sizeof (expr_t *));
或
expr_t *e = malloc (offsetof (expr_t, children) + n * sizeof (expr_t *));
?
sizeof 是否可以保证在具有灵活数组成员的类型上工作(GCC 接受它)?
【问题讨论】:
-
是的,它可以保证工作。 C99 §6.7.2.1/16 说“结构的大小应等于以未指定长度的数组替换灵活数组成员的其他相同结构的最后一个元素的偏移量。”。所以
sizeof(expr_t)等于offsetof(expr_t, children)的值,如果您将children重新定义为任意确定大小的数组。
标签: c c99 flexible-array-member