Reputation: 61
node *x = NULL;
node *x = new node();
What is the difference in these two different creations of nodes? Why do we not do the 2nd type while creating the head and use the 1st generally? Cannot we do the null assignment every time while creating a new one? Or cannot we do the "new node()" thing every time? When to use what, it's very confusing.
Upvotes: 0
Views: 59
Reputation: 58868
node *x = NULL; // 1
node *x = new node(); // 2
What is the difference in these two different creations of nodes?
The first one doesn't create a node. The second one does.
The first one creates a pointer to a node and sets the pointer to NULL, which means it doesn't point to anything.
The second one creates a pointer to a node, creates a node, and sets the pointer so it points to the node it just created.
node *x = y;
is the same as node *x;
and then x = y;
. Both of these have the node *x;
part (which creates a pointer variable), but the second part is different.
Why do we not do the 2nd type while creating the head and use the 1st generally?
You would use the first one if you want a new pointer that points to NULL, and the second one if you want a new pointer that points to a new node.
Cannot we do the null assignment every time while creating a new one? Or cannot we do the "new node()" thing every time? When to use what, it's very confusing.
It depends which one you want. This question is like asking: Can I do int i = 4;
every time? Or can't we do int i = 7 + 3;
every time? When should I use int i = 7 + 3;
instead of int i = 4;
?
Upvotes: 2
Reputation: 40080
What is the difference in these two different creations of nodes?
Typically, nullptr
denotes an empty tree; a pointer to an unique Node
is a tree with a simple leaf.
node* empty_tree = nullptr;
node* leaf = new Node;
Upvotes: 0