这是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 *));
< p> < 代码> sizeof
< p> 在具有灵活数组成员的类型上工作是否有保障(GCC接受它)?
children
重新定义为任何确定大小的数组,则sizeof(expr_t)
的值将等于offsetof(expr_t, children)
的值。 - Adam Rosenfield