cfunctionpass-by-referencesingly-linked-list

Error in using call by reference with function to change the head of a singly linked list


I'm learning linked lists in C, and have come across an error when trying to add a value at beginning of a linked list using functions

#include<stdio.h>
#include<stdlib.h>
struct node{
    int val;
    struct node *next;
};
void printlist(struct node *head){
    struct node *current = head;
    while(current!=NULL){
        printf("%d\n",current->val);
        current = current->next;
    }
    printf("------------------------\n");
}
void addatbegin(struct node **head,int x){
    struct node *new;
    new = (struct node*)malloc(sizeof(struct node));
    new->val = x;
    new->next = *head;
    *head = new;
}
int main(){
    struct node *head;
    struct node *h;
    h = &head;
    head = (struct node*)malloc(sizeof(struct node));
    head->val=2;
    head->next= (struct node*)malloc(sizeof(struct node));
    head->next->val = 3;
    printlist(head);
    addatbegin(h,4);
    printlist(head);
}

in the function addatbegin(struct node **head,int x), i gave a double pointer to try and use pass by reference to change the head of the linked list.The code runs and works, However im getting these errors/warnings.

main.c: In function ‘main’:
main.c:33:7: warning: assignment to ‘struct node *’ from incompatible pointer type ‘struct node **’ [-Wincompatible-pointer-types]
   33 |     h = &head;
      |       ^
main.c:40:16: warning: passing argument 1 of ‘addatbegin’ from incompatible pointer type [-Wincompatible-pointer-types]
   40 |     addatbegin(h,4);
      |                ^
      |                |
      |                struct node *
main.c:23:31: note: expected ‘struct node **’ but argument is of type ‘struct node *’
   23 | void addatbegin(struct node **head,int x){
      |                 ~~~~~~~~~~~~~~^~~~
2
3
------------------------
4
2
3
------------------------

How do I fix this?


Solution

  • The compiler warning is telling you what you need to know. You're passing a struct node * rather than a struct node **. You need to use & to pass the address of the head pointer.

    int main(void) {
        struct node *head = malloc(sizeof(struct node));
        if (!head) {
            return 1;
        }
    
        head->val = 2;
        head->next = malloc(sizeof(struct node));
        if (!head->next) {
            free(head);
            return 1;
        }
    
        head->next->val = 3;
        head->next->next = NULL;
        printlist(head);
        addatbegin(&head, 4);
        printlist(head);
    
        free(head->next);
        free(head);
    }
    

    Other notes: