title: c++ pointers and variable scope
body: <p>I am trying to create a tree structure using some handler functions that are called while reading a stream. I think the problem is that my variables are created in the function's scope and disappear when the function ends, leaving pointers that point to nothing.</p>
  
  <p>I am not sure what approach to take to keep the objects in memory, whilst still allowing the tree to be scalable.</p>
  
  <p>I have made a simplified version of the code: it compiles and runs but the parent-child relationships of the 'Segment' objects are all wrong.</p>
  
  <pre><code>class Segment
  {
  public:
      Segment* parent;
      list&lt;Segment*&gt; children;
      string name;
  };
  
  void OpenSegment(Segment* p_segCurrentseg);
  void CloseSegment(Segment* p_segCurrentseg);
  
  int _tmain(int argc, _TCHAR* argv[])
  {
      Segment parent;
      parent.name="parent";
      Segment* p_segCurrentseg=&amp;parent;
      OpenSegment(p_segCurrentseg);
      OpenSegment(p_segCurrentseg);
      OpenSegment(p_segCurrentseg);
      CloseSegment(p_segCurrentseg);
      return 0;
  }
  
  void OpenSegment(Segment* p_segCurrentseg)
  {
      Segment child;
      child.name="child";
      p_segCurrentseg-&gt;children.push_front(&amp;child);
      child.parent=p_segCurrentseg;
      p_segCurrentseg=&amp;child;
  }
  
  void CloseSegment(Segment* p_segCurrentseg)
  {
      p_segCurrentseg=p_segCurrentseg-&gt;parent;
  }
  </code></pre>