cpointersdata-structures

Issue with incompatible pointer type


I have this code:

#include<stdio.h>
#include<stdlib.h>

typedef struct{
    int data;
    struct node *next;
} NODE;

NODE *head = NULL;

void display_ll(NODE *head){
    if (head == NULL){
        printf("\nList is empty");
    } else{
        for(NODE *curr=head; curr!=NULL; curr=curr->next){
            printf("%d ->", curr->data);
        }
        printf("\b\b  ");
    }
}

int main(void){
    NODE *temp = (NODE *)malloc(sizeof(NODE));
    temp->data = 5;
    temp->next = NULL;
    head = temp;
    display_ll(head);
    return 0;
}

On line 15, where I do curr=curr->next in the for loop, I am getting a warning if compiled using clang, and an error if compiled using gcc:

  1. clang:
    warning: incompatible pointer types assigning to 'NODE *' from 'struct node *' [-Wincompatible-pointer-types]
    
  2. gcc:
    error: assignment to ‘NODE *’ from incompatible pointer type ‘struct node *’ [-Wincompatible-pointer-types]`
    

I figured a workaround where we write the structure as typedef struct node {...} NODE; and it works. But I want to know if there's any fix to this without this struct redefinition.


Solution

  • Your struct name is not node.
    In fact it is unnamed (struct{ ... }), and NODE is an alias to that unnamed struct.

    Therefore in this line:

    struct node *next;
    

    next is not a pointer to the current struct as you seem to expect (it is a pointer to some other assumed struct node which is forward declared here).

    In order to fix it, simply give the name to your struct:

    //-------------vvvv
    typedef struct node {
        int data;
        struct node *next; 
    } NODE;
    

    This will make next a pointer to the current struct as you expect.

    Live demo

    A side note:
    You should always enable and note compiler warnings. In display_ll the parameter head is hiding the global one. Even if this is what you meant to happen, it is recommended to change the name of the parameter to avoid confusion.