这是 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 接受它)?