In my code a have a global vector of Node object and a local vector of Node pointers:
#include<cstdio>
#include<cstdlib>
#include<vector>
using namespace std;
class Node {
int n;
public:
Node(int i) : n(i);
int getN() { return n; }
};
vector<Node> v;
int main() {
vector<Node*> p;
v.push_back(Node(1));
p.push_back(&v[0]);
printf("first node id : %d\n", (*p[0]).getN());
return 0;
}
I inserted a node object to global vector & inserted the pointer of that object in the local vector. Output of my above code is:
first node id : 1
However, if I change my main function to this:
int main()
{
vector<Node*> p;
v.push_back(Node(1));
p.push_back(&v[0]);
v.push_back(Node(2));
p.push_back(&v[1]);
printf("first node id : %d\n", (*p[0]).getN());
return 0;
}
The code prints a garbage value:
first node id : 32390176
I can't figure out the problem.
Does the vector
data structure changes the references of each object after an insertion ?
How can I fix this ?