Search code examples
cstructdeclarationtypedefdefinition

error: dereferencing pointer to incomplete type - C language


A few days ago I made a function, which worked just fine. This is struct defining I used.

typedef struct {
    int data;
    struct Node * next;
} Node;

typedef struct {
    Node * head;
    Node * current;
    int size;
} List;

Then I have this function

void returnMiddle(List * list){
    Node * first = list->head;
    Node * second = list->head;

    if(list->head != NULL){
        while(second != NULL && second->next != NULL){
            first = first->next;
            second = first->next->next; 
        }
        printf("Middle is: %d", first->data);
    }
}

But now I receive given error and I don't understand why? Does anyone know?

second = first->next->next; <<< this is where I get an error message, up to here it works fine


Solution

  • In this typedef declaration of a structure

    typedef struct {
        int data;
        struct Node * next;
    } Node;
    

    the type struct Node is an incomplete type. That is the type name struct Node is introduced but not defined.

    Pay attention that the typedef name Node and the type name struct Node name two different entities. The name Node names an unnamed structure while struct Node names a not yet defined structure.

    It is obvious that you mean the following

    typedef struct Node {
        int data;
        struct Node * next;
    } Node;