title: Creating a list in C++
body: <p>I am currently learning about pointers and structures, and I am working on an exercise.
  My goal is to write a function head_insert which basically creates a new list element and it appends it to the front.</p>
  
  <p>Note: I know that there's already a datatype list in c++, however this is just for exercising and understanding the concept behind dynamic structures better.</p>
  
  <p>My code is the following:</p>
  
  <pre><code>struct list{
      int val;
      list *next = NULL;
  };
  
  typedef list* ptr_list;
  
  ptr_list head_insert(ptr_list head, const int element){
      ptr_list tmp_head;
      tmp_head = new list;
      tmp_head-&gt;val = element;
      tmp_head-&gt;next = head;
      return tmp_head;
  }
  
  int main(){
      ptr_list head = NULL;
      head = head_insert(head, 1); // This is the crucial step I think, as head is not initialized yet
      head = head_insert(head, 2);
  
      return 0;
  }
  </code></pre>
  
  <p>The thing is, I want the function head_insert also to work when head is NULL, i.e. my list is empty. However, when debugging my code, I notice that after each call of head_insert head stays NULL, however changes within head(head->val, head->next) are made.</p>
  
  <p>Why is that? Has that something to do with the scope of tmp_head?
  How could i modify my code to work in the way I intended?</p>
  
  <p>If I dont set head to NULL in the beginning, but allocate space and setting it manually to the first element, everything works perfectly fine:</p>
  
  <pre><code>head = new list;
  head-&gt;val = 1;
  </code></pre>
  
  <p>Thanks for your time and help!
  Cheers</p>