Can you assign a NULL pointer variable to a pointer variable?

748 Views Asked by At

So I was working on the Max Heap Tree with link representation on C++. Since I cannot upload the code as it is pretty long but while I was debugging I realized that the execution will stop at the expression where it assgins Null pointer to a pointer. for example

// if node->left_child->right_chile == NULL
node->right_child = node->left_child->right_child; // the program will exit here.

This kind of operation often occurs in my code at the deletion method so I was also wondering if I assign NULL variable multiple times, it causes error. for example in continuition of above example,

node->parent->left_child = node->right_child;

I was trying to figure out how NULL pointer behaves but I cannot quite get it. Could you please help me?

1

There are 1 best solutions below

0
On

Can you assign a NULL pointer variable to a pointer variable?

Yes. You can assign a pointer to another as long as the value of the that is assigned from has been initialised. If that value is null, it is OK. For example, this is fine:

Node* a = nullptr;
Node* b = nullptr;
a = b;
node->right_child = node->left_child->right_child; // the program will exit here.

This implies that one of node or node->left_child is probably not a valid pointer. Either of those would result in undefined behaviour.


P.S. Don't use the NULL macro in C++. It has bee obsoleted by nullptr.