Question

I starting study pointers and linked list in C but i have a problem:

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;
}

why is the output:

In function, head is NULL
In main, head is NOT NULL

I expect this: In function, head is NULL In main, head is NULL

This is my first experience with pointers in C and can't understand what i wrong

Was it helpful?

Solution

In your pop function you want to modify your head variable. Since C is passing parameters per value, you must give the address of head variable in order to modify its value. The same thing applies for tail.

Thus change your pop function from:

int pop(struct pointer *head, struct pointer *tail)

to:

int pop(struct pointer **head, struct pointer **tail)

And when calling this function, use pop(&head, &tail);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top