0

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

Miek
  • 1,127
  • 4
  • 20
  • 35
  • That's not exactly the same question. No-one has addressed any explanation as to why the simple int pointer works and a node pointer does not. In fact one response shows passing the int pointer as a pointer reference and that does not appear to be necessary according to what im debugging. – Miek Jan 20 '17 at 07:42
  • 1
    "The value of `ptr` is updated to 11 from 7" - This is incorrect. The value of `test` is being updated. The value of `ptr` remains the same: it is a pointer to `test` (i.e. a memory pointer to the memory area that `test` occupies). For `listHead` to be updated, yes, you would have to pass `&listHead` as a `Node ** head` to `addNode()`. Because you're modifying the value of `listHead` in that function. – Ates Goral Jan 20 '17 at 07:57

0 Answers0