Search code examples
c++pointersoperator-precedenceunary-operator

Why can't pointer to pointer, access struct members without a cast?


In C++, I was trying to access the struct members through double pointer headref as shown below

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

struct Node* head = new Node;
head->data = 10; 
head->next = NULL; 

struct Node** headref = &head; 

However, accessing as *headref->data produces errors while casting it ((Node*)*headref)->data works. Why?


Solution

  • This expression

    *headref->data
    

    is equivalent to

    *( headref->data )
    

    It is not the same as the valid expression

    ( *headref )->data
    

    because the data member data has no pointer type and you may not apply the unary operator * to it.

    This expression

    ((Node*)*headref)->data
    

    is valid not due to the casting. It is valid because if to remove the casting that is redundant you will get the valid edxpression

    ( /*(Node*)*/ *headref)->data
    

    shown above.