Search code examples
c++c++11pointersoperator-precedencedereference

What is wrong in this code related to pointer


/* The structure of the Linked list Node is as follows:

struct Node
{
    int val;
    struct Node *next;

    Node(int data){
        val = data;
        next = NULL;
    }

}; 
*/

void intersection(Node **head1, Node **head2,Node **head3)
{

    cout<<*head1->val;
}

The above code in not working but when I take another pointer Node* h1=*head1; and then print its value its working fine. In both codes the value I want to print is same then why above code is wrong;

/* The structure of the Linked list Node is as follows:

struct Node
{
    int val;
    struct Node *next;

    Node(int data){
        val = data;
        next = NULL;
    }

}; 
*/

void intersection(Node **head1, Node **head2,Node **head3)
{

    Node* h1=*head1;
    cout<<h1->val;
}

Solution

  • In this code snippet

    void intersection(Node **head1, Node **head2,Node **head3)
    {
    
        cout<<*head1->val;
    }
    

    the expression

    *head1->val
    

    is equivalent to

    *( head1->val )
    

    (because the postfix operator -> has higher priority than the unary operator *) but the pointer head does not point to an object of the structure type. It points to another pointer, You have to write

    ( *head1 )->val
    

    This is equivalent to the expression with the intermediate variable h1

    Node* h1 = ( *head1 );
    h1->val;
    

    To make the difference more visible you can rewrite the expression of accessing the data member val the following way

    ( **head ).val
    

    that is now the expression **head yields the lvalue of an object of the type struct Node.

    Or using an intermediate variable like

    Node *h1 = *head;
    ( *( h1 ) ).val
         ^
         |
       *head