Search code examples
cstructlinked-listtypedefdefinition

Incompatible pointer types struct node to node


I'm doing a lab for my course and I'm having an issue with some warnings. We are given a struct that we cannot change:

typedef struct Element{
    int value;
    double key1;
    double key2;
    struct NODE* next;
    struct NODE* sort1;
    struct NODE* sort2;
}Node;

And this is the main code:

struct Element * randomizer(int A){
     /*Function to have "real" random*/

    srand((unsigned int) time(0));

     Node *head;
     Node *ptr;
    int i = 0;

    head = NULL;
    ptr = NULL;



    /*Vlaues beiong intialized*/
    for ( i = 0 ; i <= A; i++){
    ptr = malloc(sizeof(Node));
        ptr->value = rand()%11;
        while (ptr->value == 0 || ptr->value == 10 ){
            ptr->value = rand()%11;
        }
    ptr->key1 =  (rand()%41)+10;

        while (ptr->value == 10.0 || ptr->value == 50.0 ){
              ptr->key1 =  (rand()%41)+10;
        }
    ptr->key2 = (rand()%41)+50;

        while (ptr->value == 50.0 || ptr->value == 90.0 ){
                     ptr->key2 =  (rand()%41)+50;
               }

    ptr->next = head;

    head = ptr;
    }

    ptr->sort1 = NULL;
    ptr->sort2 = NULL;

    return ptr;
}

At ptr->next = head; I get an error saying

incompatible pointer types assigning type node to struct node

How can I do this correctly?


Solution

  • In this typedef declaration

    typedef struct Element{
        int value;
        double key1;
        double key2;
        struct NODE* next;
        struct NODE* sort1;
        struct NODE* sort2;
    }Node;
    

    You declared two different structures. The first one has the type struct Element with the type alias Node and within its definition you declared the type struct NODE.

    Even if there was not a typo and the data members have the type struct Node * instead of struct NODE * nevertheless the types struct Node and Node are not the same types.

    You should declare the structure like

    typedef struct Element{
        int value;
        double key1;
        double key2;
        struct Element* next;
        struct Element* sort1;
        struct Element* sort2;
    }Node;