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.
I am not sure what approach to take to keep the objects in memory, whilst still allowing the tree to be scalable.
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.
class Segment
{
public:
Segment* parent;
list<Segment*> 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=&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->children.push_front(&child);
child.parent=p_segCurrentseg;
p_segCurrentseg=&child;
}
void CloseSegment(Segment* p_segCurrentseg)
{
p_segCurrentseg=p_segCurrentseg->parent;
}
new.