Search code examples
cpointersdereference

How to cascade -> operator?


I have the following:

typedef struct Node_struct
{
    int number;
    Node *nextNode;
    Node *prevNode;
} Node;

and later

Node *nodeInSet = lookup(set, number);
nodeInSet->nextNode = (Node *) malloc(sizeof(Node));
nodeInSet->nextNode->prevNode

the last line is saying: "expression must have pointer-to-class type". I can't see how my code is wrong. Since nodeInSet->nextNode is a Node *, I think I should be allowed to write nodeInSet->nextNode->prevNode. What is not working here?


Solution

  • The prevNode and nextNode members have incomplete type, you have to write it like this

    typedef struct Node_struct
    {
        int number;
        struct Node_struct *nextNode;
        struct Node_struct *prevNode;
    } Node;
    

    or

    typedef struct Node_struct Node;
    struct Node_struct
    {
        int number;
        Node *nextNode;
        Node *prevNode;
    };
    

    The reason is that you can declare a poniter to an incomplete type, but if you try to dereference the pointer, like when you use the -> operator, then the type must be known, because the size of the type is needed.