Assigning a new object to a pointer pointer type in cpp crushes the program. Code looks like this:
#include <iostream>
using namespace std;
struct Node{
int key;
Node * nex;
};
int main(){
Node * my_node = new Node;
Node ** pp_node;
*pp_node = my_node;
return 0;
}
I think that the issue here is following: pp_node
is null and by typing *pp_node = my_node;
I am trying to dereference null but the question is how can I assign my_node
to the pointer, pp_node
is pointing at?
pp_node
should contain the address of my_node
, in order to have pp_node
point at my_node
(which is itself a pointer and holding an address).
#include <iostream>
struct Node{
int key_;
Node * nex;
};
int main(){
Node node={34, nullptr};
Node* p_my_node = &node;
Node** pp_node;
pp_node = &p_my_node;
std::cout<<(**pp_node).key_;
return 0;
}
Now
p_my_node
is a piece of memory whose value(data it is holding) is address of node
. So it points at node
pp_node
is a piece of memory whose value is address of p_my_node
, So it points at p_my_node
the output of the code above is 34
, as we expected.