假设我的结构如下:
struct line {
int length;
char contents[];
};
struct line *thisline = (struct line *) malloc (sizeof (struct line) + this_length);
thisline->length = this_length;
分配的空间在哪里contents?在堆中还是在后面的地址中length?
根据定义,灵活数组contents[]位于可变大小结构内部,在length字段之后,因此您就在它的malloc-ing 空间中,所以当然p->contents位于您malloc-ed 的区域内(所以在堆内)。
两个都。它在堆中,因为thisline指向堆中分配的缓冲区。您在malloc()调用中请求的额外大小用作thisline->contents. 因此,thisline->contents在 之后开始thisline->length。
没有为内容隐式分配的空间。
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.