I am trying to construct a simple linked list, using a pointer pointing to the next insertion location, and add a node one by one.
Tnode* NULL_cp = 0;
struct Tnode{
string word;
Tnode* left;
Tnode* right;
};
int main(int argc, char** argv){
int n = 0;
Tnode head;
head.word = "the head";
head.left = NULL_cp;
head.right = NULL_cp;
Tnode* insertP = &head;
while(n<argc-1){
Tnode node;
node.word = argv[n+1];
node.left = insertP;
node.right = NULL_cp;
insertP->right = &node;
insertP = &node;
cout << "inside loop: " << insertP->word << endl;
n++;
}
cout << "outside loop: the word is " << insertP->word << endl;
}
the output is
inside loop: hello
outside loop: the word is
if I typed in a.out hello. the part that confused me is that after one loop, the insertP should be pointing at the newly inserted node that has the the word hello, but it printed out nothing even though inside the loop it printed out hello, any idea why? Thank you very much
Let’s minimize the problem:
When
nodegoes out of scope, so does itsstd::stringmember. You’ll have dangling pointers to nodes in your tree. Inside the loop it works because the object is still alive. Outside… not so much.Use dynamic allocation:
And don’t forget to
deleteat the end.