我在C中开始学习指针和链接列表,但我有一个问题:
struct pointer
{
int id;
struct pointer *next;
};
int pop(struct pointer *head, struct pointer *tail);
main()
{
struct pointer *head = NULL;
head = (struct pointer*)malloc(sizeof(struct pointer));
head->id=1;
struct pointer *tail = head;
tail->next=NULL;
pop(head,tail);
if (head==NULL) printf ("In main, head is NULL");
else printf ("In main, head is NOT NULL");
}
int pop(struct pointer *head, struct pointer *tail)
{
int toReturn;
struct pointer *toFree;
if (head!=NULL)
{
toReturn = head->id;
toFree = head;
head = head->next;
free(toFree);
if (head==NULL)
tail = head;
}
else toReturn = -1;
if (head==NULL) printf ("In function, head is NULL\n");
else printf ("In function, head is NOT NULL\n");
return toReturn;
}
为什么输出:
In function, head is NULL
In main, head is NOT NULL
我期待这个: 在函数中,head为NULL 在main中,head为NULL
这是我第一次使用C指针进行操作,无法理解我的错误
答案 0 :(得分:5)
在pop
功能中,您要修改head
变量。由于C是按值传递参数,因此必须提供head
变量的地址才能修改其值。同样适用于tail
。
从而改变你的pop功能:
int pop(struct pointer *head, struct pointer *tail)
为:
int pop(struct pointer **head, struct pointer **tail)
调用此函数时,请使用pop(&head, &tail);