title: Structure initialization does not work with malloc
body: <p>I've a small background in C that I'm trying to dig up, and I encountered something I can't explain.</p>
  
  <p>Let's say I have the following structure:</p>
  
  <pre><code>struct World {
     Things* things;
  };
  </code></pre>
  
  <p>and the following functions:</p>
  
  <pre><code>void initWorld(World *world);
  
  void addThingToWorld(World *world, Thing *thing);
  </code></pre>
  
  <p>Now, depending on the implementation of <code>initWorld</code> and how I use it, it will either work or not. But I don't understand why the second implementation should fail. Both implementations are below:</p>
  
  <h2>First (working) implementation</h2>
  
  <pre><code>void initWorld(World *world){
      world-&gt;things = NULL;
  }
  
  // usage
  World world;
  initWorld(&amp;world);
  // will work, because world has been correctly initialized.
  addThingToWorld(&amp;world, &amp;something);
  </code></pre>
  
  <h2>Second (failing) implementation</h2>
  
  <pre><code>void initWorld(World *world){
      world = (World*) malloc(sizeof(World));
      world-&gt;things = NULL; // here it does not work! things is not changed to 0x0 :(
  }
  
  // usage
  World *world;
  initWorld(world);
  // this will crash as a side-effect of the failed world initialization (world-&gt;things has not been correctly set to NULL)
  addThingToWorld(world, &amp;something);
  </code></pre>
  
  <p>Thank you for your help, and correct any nonsense I might be doing, my C background is pretty poor at the moment :)</p>
  
  <h1>Edit</h1>
  
  <p>Okay I understood the fact that I was passing a pointer to my function in the second case, and re-assigning it with a local malloc so in the end the caller's variable was not changed. However as I was debugging there is still something I don't understand. In the <code>initWorld</code> function, the second case, the <code>world-&gt;things</code> value did not change after the assignation to NULL. <strong>I also tried to rename the local variable</strong> world to "w", I thought that maybe the debugger was displaying the caller's variable "world", but no, <code>w-&gt;things</code> still was not correctly initialized to NULL.</p>
  
  <p>Any hints?</p>