【发布时间】:2015-10-28 10:01:54
【问题描述】:
“a”是链表的头节点。所有节点的内存都是通过 malloc 分配的。在构建列表 (10 20 30 40) 之后,我将它传递给另一个函数,在该函数中我将它分配给一个在本地声明的节点“当前”并且没有执行 malloc。但是我能够正确遍历整个列表。 “当前”访问的是堆内存中的链表吗?
void main()
{
struct node* a = (struct node*) malloc (sizeof(struct node));
struct node* temp = (struct node*) malloc (sizeof(struct node));
a->data = 10;
temp->data = 20;
a->next = temp;
temp = (struct node*) malloc (sizeof(struct node));
temp->data =25;
temp = (struct node*) malloc (sizeof(struct node));
temp->data = 30;
a->next->next = temp;
temp = (struct node*) malloc (sizeof(struct node));
temp->data = 40;
a->next->next->next = temp;
a->next->next->next->next = NULL;
printlist(a);
}
void printlist(struct node* head)
{
struct node* current = head;
while (current != NULL)
{
printf("%d ",current->data);
current = current->next;
}
}
【问题讨论】:
-
"
current是在访问堆内存中的链表吗?"。是的。这就是指针的工作原理。指针存储内存位置的地址。在这种情况下,current设置为指向与head指向的位置相同的位置。
标签: c pointers linked-list heap-memory stack-memory