2012-10-18 38 views
3

假设我有一个结构如下:C中灵活长度数组的分配空间在哪里?

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

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

哪里是为contents分配的空间?在堆或在length后的地址?

+0

数组长度丢失;它必须是'1'。 –

+1

它不缺,它是一个灵活的数组成员。 – ouah

+2

@SethCarnegie不在C99或更高版本。 –

回答

4

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

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. 
+1

没有*隐式*分配的空间。 –

+2

灵活与否,你不能分配给一个数组。 – ouah

+0

谢谢你们! :-)相应地修改了我的答案 –

6

的柔性阵列contents[]是由位于所述可变大小的结构内定义,length后场,所以你是对在malloc它-ing空间,所以当然p->contents坐在内的区域,你malloc -ed(所以在堆内)。

+0

@丹尼尔:谢谢,相应编辑。 –