I have a program like below, when I try to access a struct member using pointer to pointer it says the expression must have a pointer to class type. Please tell me how can I access data element of the struct object using a pointer to pointer
#include "stdafx.h"
#include<iostream>
struct Node{
int data;
Node* next;
};
void addnode(Node** node, int val)
{
if (node == NULL){
*node = new Node();
*node->data = val;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Node* node;
addnode(&node, 10);
return 0;
}
In *node->data = val;
there are 3 operators involved.
operator*
to dereferenceoperator->
to access a memberoperator=
to do the assignmentIn which order will these happen? According to operator precedence which states:
Precedence | Operator |
---|---|
2 | operator-> |
3 | operator* |
16 | operator= |
node->data
will happen first and then the result will be dereferenced - so you have *(node->data)
on the left hand side.
You need to dereference node
first and can use (
... )
to override the precedence rules:
(*node)->data = val;
Also note that your original Node*
is uninitialized and reading it (like you do in if(node == NULL)
) will cause the program to have undefined behavior. Initialize it to nullptr
:
Node* node = nullptr; // here
addnode(&node, 10);