【发布时间】:2019-06-28 20:55:46
【问题描述】:
我正在浏览 SO,发现 some code 向我提出了一个问题。
struct node* BuildOneTwoThree() {
struct node *list = malloc(3 * sizeof(struct node));
list[0].data = 1;
list[0].next = list+1;
list[1].data = 2;
list[1].next = list+2;
list[2].data = 3;
list[2].next = NULL;
return list;}
我试图了解这个对 malloc 的调用是如何工作的以及它返回什么。它是否返回了一个指针数组?那是怎么回事,我没想到malloc会以这种方式工作?
这似乎保证了各个结构的内存索引是一个接一个的,我认为这可能是一个强大或有用的工具。
同样在调用 malloc 之后,将数组索引初始化为
list[0] = (struct node) {1, list +1};
注意:结构节点定义为,
struct node{
int data;
struct node *next;};
【问题讨论】:
-
它返回一个指向
3 * sizeof(struct node)字节分配内存的指针。 -
为什么我可以使用数组索引来索引这些指针?
-
因为
list[i]等价于*(list+i)。 -
malloc()在第一次调用中返回的空间足够大,可以容纳 3 个struct node的数组,并且指向的内存足够对齐,可以安全地将其转换为struct node *并将其用作 3 个struct node值的数组。 C 标准要求保证“充分对齐”。
标签: c memory-management linked-list malloc nodes