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

Viewed 130

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?

2 Answers

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.

If you chain operators together, it's always a good idea to make sure you remember their precedence correctly. As listed here, operator-> has a higher precedence than the indirection *. Hence

*headref->data

is interpreted as

*(headref->data)

which can't work. Instead, use

(*headref)->data

which is equivalent to ((Node*)headref)->data.

Related