Pointers and Linked List in C

I start tutorial pointers and a 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 conclusion:

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

I expect this: In a function, the head is NULL Mostly the head is NULL

This is my first experience with pointers to C and I can’t understand that I'm wrong

+3
source share
1 answer

In your function, popyou want to change your variable head. Since C passes parameters for the value, you must specify the address of the variable headin order to change its value. The same applies to tail.

So change your pop function:

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

at

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

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

+5
source

All Articles