title: Inserting into a binary search tree in C
body: <p>I'm currently learning C and also some datastructures such as binary search trees etc. I have trouble understanding HOW exactly changing pointer values within a function works in some cases and in others doesn't... I'll attach some of my code I wrote. It's an insert function which inserts values in the correct places in the BST (it works as it should). I tried working with pointers to pointers to be able to change values withing a function. Even though it works, im still really confused why it actually does.
  I don't quite understand why my insert function actually changes the BST even though I only work with local variables (tmp, parent_ptr) in my insert function and I don't really dereference any pointers apart from &quot; tmp = *p2r &quot; in the insert function.</p>
  <p>Thanks for helping out.</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  
  struct TreeNode{
      int val;
      struct TreeNode *left;
      struct TreeNode *right;
  };
  
  struct TreeNode** createTree(){
      struct TreeNode** p2r;
      p2r = malloc(sizeof(struct TreeNode*));
      *p2r = NULL;
      return p2r;
  }
  
  void insert(struct TreeNode** p2r, int val){
      // create TreeNode which we will insert
      struct TreeNode* new_node = malloc(sizeof(struct TreeNode));
      new_node -&gt; val = val;
      new_node -&gt; left = NULL;
      new_node -&gt; right = NULL;
      //define onestep delayed pointer
      struct TreeNode* parent_ptr = NULL;
      struct TreeNode* tmp = NULL;
      tmp = *p2r;
      // find right place to insert node
      while (tmp != NULL){
          parent_ptr = tmp;
          if (tmp -&gt; val &lt; val) tmp = tmp-&gt;right;
          else tmp = tmp-&gt;left;
      }
      if (parent_ptr == NULL){
          *p2r = new_node;
      }
      else if (parent_ptr-&gt;val &lt; val){ //then insert on the right
          parent_ptr -&gt; right = new_node;
      }else{
          parent_ptr -&gt; left = new_node;
      }
  }
  
  int main(){
      struct TreeNode **p2r = createTree();
      insert(p2r, 4);
      insert(p2r, 2);
      insert(p2r, 3);
      return 0;
  }
  </code></pre>