【发布时间】:2019-05-12 20:20:12
【问题描述】:
我正在跟踪我的教授给出的链表 C 代码,但我不确定它是如何工作的。第一部分最让我困惑。我以为 head 是 4,因为 temp 是 0,所以 head+temp 是 4。但是,ptr 是 5 而不是 4。谁能解释发生了什么? 除了代码之外,我将实际输出放在 cmets 中。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *next;
};
typedef struct node node;
int func1 (node *head)
{
int temp = 0;
while (head !=NULL)
{
temp = temp + head -> info;
head = head->next;
}
return(temp);
}
int main()
{
node *ptr,*ptr2,*ptr3; //ptr ptr2 ptr3
ptr = (node*)malloc(sizeof(node));
ptr->info = 4;//what is this??
ptr2 = (node*)malloc(sizeof(node));
ptr->next = ptr2;
ptr2->next = NULL;
ptr->next->info = 1;//5 1 <-actual list //what happened to 4??
printf("ptr2 %d\n",func1(ptr2));//1
printf("ptr %d\n",func1(ptr));//5
ptr3 = (node*)malloc(sizeof(node));//5 1 _
ptr3->next = ptr;//5 1 _ ? //but there's no space for ptr3->next??
ptr3->info = 2;//5 1 7 <-actual list
printf("ptr3 %d\n",func1(ptr3));//7
ptr2->info = 8;//12 8 14 <-actual list
printf("ptr3 %d\n",func1(ptr3));//14
ptr->info = 16;//24 8 26 <-actual list
printf("ptr2 %d\n",func1(ptr));//24
}
【问题讨论】:
标签: function loops linked-list nodes trace