I would like to show an example of updating an int pointer from a main method and then the same thing with a linked list. Please explain why updating the simple int* works and adding nodes to the head does not.
Example 1:
#include <iostream>
void changeValue(int* num);
int main(int argc, const char * argv[]) {
int test = 7;
int* ptr = &test;
std::cout << "Original value of test: "<<*ptr<<std::endl; // Value is 7
// Change Value
changeValue(ptr);
std::cout << "Value of test after update: "<<*ptr<<std::endl; // Value is 11
return 0;
}
void changeValue(int* num){
*num = 11;
}
The value of test is updated to 11 from 7. This I would expect.
Example 2:
#include <iostream>
struct Node{
int data;
Node *next;
};
void addNode(Node * head , int data);
int main(int argc, const char * argv[]) {
Node * listHead = NULL;
addNode(listHead, 34);
addNode(listHead, 67);
return 0;
}
void addNode(Node * head , int data){
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
if(head == NULL){
head = newNode;
}else{
Node* temp = head;
while(true){
if(temp->next == NULL){
temp->next = newNode;
break;
}
temp = temp->next;
}
}
}
After execution, listHead is still NULL. I have read one post that explained that when you pass a Node like this you are still passing by copy, but that makes no sense to me. I just created a node pointer. It should update just like the int pointer, right?
Another post hinted that this type of thing was a scoping problem, but I'm not seeing that clearly.
I have seen the Linked List example where the listHead is passed in as a double pointer, and this does work, but I would like to understand whats happening that makes the difference.
Thanks