C中灵活长度数组的分配空间在哪里?

时间:2012-10-18 19:49:33

标签: c arrays

假设我有如下结构:

struct line {
       int length;
       char contents[];
};

struct line *thisline = (struct line *) malloc (sizeof (struct line) + this_length);
thisline->length = this_length;

contents的分配空间在哪里?在堆中或length之后的即将到来的地址?

3 个答案:

答案 0 :(得分:6)

根据定义,灵活数组contents[]位于变量大小的结构内,位于length字段之后,因此您就在malloc -ing空间中,因此当然{ {1}}位于您p->contents - 的区域内(因此在堆内)。

答案 1 :(得分:4)

两者。它位于堆中,因为thisline指向堆中的已分配缓冲区。您在malloc()调用中请求的额外大小用作thisline->contents的分配区域。因此,thisline->contentsthisline->length之后开始。

答案 2 :(得分:0)

NO 隐式分配内容空间。

struct line foo;
// the size of foo.contents in this case is zero.

始终通过使用指针来引用它。 例如,

struct line * foo = malloc( sizeof(foo) + 100 * sizeof(char) );
// now foo.contents has space for 100 char's.
相关问题