So I was learning how to make a linked list, and I was wondering why we need to use "new" when adding a node. Below is function that adds a node correctly:
void addNode(int value){
Node* new_node_ptr = new Node;
new_node_ptr->value = value;
if (root == NULL){
root = new_node_ptr;
traveler = new_node_ptr;
} else {
traveler->next = new_node_ptr;
traveler = new_node_ptr;
}
}
But, since I am new to c++, when I tried to figure out how to do this by myself, instead of having the line:
Node* new_node_ptr = new Node;
I wrote:
Node new_node;
Node* new_node_ptr = &new_node;
This doesn't work. It seems that the new_node variable keeps being assigned to the same memory address each time you try to add a new node. This is simultaneously fascinating and infuriating. Could anybody explain this c++ weirdness to me?
Thanks!