C中的指针和链表

Pas*_*sor 3 c pointers singly-linked-list

我在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;
}
Run Code Online (Sandbox Code Playgroud)

为什么输出:

In function, head is NULL
In main, head is NOT NULL
Run Code Online (Sandbox Code Playgroud)

我期望这样:在函数中,head为NULL在main中,head为NULL

这是我第一次使用C语言指针,无法理解我的错误

bag*_*age 5

在您的pop函数中,您想要修改head变量.由于C是每个值传递参数,因此必须提供head变量的地址才能修改其值.同样的事情也适用tail.

从而改变你的pop功能:

int pop(struct pointer *head, struct pointer *tail)
Run Code Online (Sandbox Code Playgroud)

至:

int pop(struct pointer **head, struct pointer **tail)
Run Code Online (Sandbox Code Playgroud)

在调用此函数时,请使用 pop(&head, &tail);

  • @PascalNoPascensor应该是`(*head) - > id;` (2认同)