灵活的数组成员分配结构 [英] Allocating struct with flexible array member

查看:142
本文介绍了灵活的数组成员分配结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是C99 code:

This is C99 code:

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 *));

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

的sizeof 甚至保证与灵活的阵列成员的类型(GCC接受它)?

Is sizeof even guaranteed to work on an type with flexible array member (GCC accepts it) ?

推荐答案

expr_t * E =的malloc(sizeof的(expr_t)+ N * sizeof的(expr_t *)); 很好C99中定义。从C99规范6.7.2.1.16:

expr_t *e = malloc (sizeof (expr_t) + n * sizeof (expr_t *)); is well defined in C99. From the C99 specification 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.

这篇关于灵活的数组成员分配结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆