In a program to simulate logic gates I switched from using arrays
node N[1000];
to vectors
vector<node> N;
And my program did work perfectly before using vectors but now it prints wrong results, so I tried debugging and I found out that the bug happens here:
node* Simulator::FindNode(string h)
{
int i;
for(i = 0; i < NNodes; i++)
{
if (N[i].getname() == h)
{
return &N[i];
}
}
node n ;
N.push_back(n);
N[NNodes].setname(h);
NNodes++;
return &N[NNodes-1]; //why?because of NNodes++
}
// ...
node* inp1;
node* inp2;
node* out;
string NodeName;
inp_file >> NodeName;
inp1 = FindNode(NodeName);
s1 = inp1;
inp_file >> NodeName;
inp2 = FindNode(NodeName); //inp1 is destroyed here
inp_file >> NodeName;
out = FindNode(NodeName); //inp2 and inp1 are destroyed here
When calling FindNode
for the 1st time, the 1st pointer inp1 points to the right place which is &N[0]
.
When calling FindNode
for the second time the 1st pointer inp1 points to rubbish and the second pointer inp2 points to the right place &N[1]
.
When calling FindNode
for the 3rd time the both the 1st and 2nd pointers (inp1
, inp2
) point to rubbish! And 3rd pointer out points to the right place.
Why would that happen?
How does vector work when I insert items to them and which kind of pointers should I use to point to vectors items?