[英]Pointers and Linked List in C
我在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语言指针,无法理解我的错误
在您的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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.