0

So, I'm dealing with trees and when doing insertions I need to modify a node that I pass as parameter.

What's happening:

(For simplicity's sake, I'll exemplify with the case that adds the first node of the tree)

After insert_node_loop I check tree->root and it still points to NULL, even though both node and x are correct. So, my thoughts are that maybe node is not updating the argument, just its "local" variable. But I don't know what to do. Could anybody enlighten me?

int insert(TREE* tree, ITEM* item){
   NODE* x = insert_node_loop(tree->root, NULL, item);
   // ...
}

NODE* insert_node_loop(NODE* node, ITEM* item){
   if(node == NULL){
      node = create_node(item);
   }
   // ... 

   return node;
}
plethora
  • 135
  • 1
  • 8

1 Answers1

3

You need to use a pointer to a pointer, that way you can modify its value:

int insert(TREE* tree, ITEM* item){
   NODE* x = insert_node_loop(&tree->root, NULL, item);
   // ...
}

NODE* insert_node_loop(NODE** node, ITEM* item){
   if(*node == NULL){
      *node = create_node(item);
   }
   // ... 

   return *node;
}
Marcelo Cerri
  • 162
  • 1
  • 10