Search code examples
cpointerspass-by-value

Values vanishing after leaving function


I'm writing a function to insert into a tree and the data can be seen (printed) after insertion within the function but when trying to see it in main nothing happens.

node *tree = NULL;
insert(tree, 4321);
printf("outer: %d\n", tree->data);

void insert(node* tree, int data) {
  if (tree == NULL) {
    tree = new_node(data);
    printf("inner: %d\n", tree->data);
  }
}

This gives:

inner: 4321

It should be:

inner: 4321
outer: 4321

Solution

  • The problem is, tree is passed as an argument to the function, and by-status which is a pass-by-value in C. Any change made to tree itself inside the function will not be reflected back to the caller.

    You need to pass a pointer to tree, if you want to modify tree from the called function.

    Something like

    void insert(node** tree, int data) {
      if (*tree == NULL) {
        *tree = new_node(data);
        printf("inner: %d\n", (*tree)->data);
      }
    }
    

    and call it like

    insert(&tree, 4321);