-3

I declared a struct treenode

struct treenode {
    int val;
    treenode *l;
    treenode *r;
};

and a vector

vector<int> v = { 1,2,3,4,5,6,7,8,9 };

now I want to create a vector tv to store the value of v

vector<treenode* > tv;
for (int i = 0; i < v.size(); i++)
    {
        treenode mid;
        mid.val = v[i];
        mid.l = NULL;
        mid.r = NULL;
        tv.push_back(&mid);
    }

but when I print the value of tv, I found all the element of tv are same(same address), there are 9. I`m confused, I have create a new treenode every iteration, why all the element use same address enter image description here

1 Answers1

4

You have a vector of dangling pointers. Just store them by value

vector<treenode> tv;
for (int i = 0; i < v.size(); i++)
{
    treenode mid;
    mid.val = v[i];
    mid.l = NULL;
    mid.r = NULL;
    tv.push_back(mid);
}

Otherwise you keep pushing back pointers to a temporary variable mid that falls out of scope between iterations.

Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021
Cory Kramer
  • 107,498
  • 14
  • 145
  • 201