Reputation: 79
I can't find any practical use for this, but I'm still curious as to why I'm getting different results when run in the same statement scope as apposed to different statement scopes?
int num = 3;
vector<int> ivec;
vector<int*> ipvec;
for (int i = 0; i != num; ++i)
{
ivec.push_back(i);
ipvec.push_back(&ivec[i]);
}
for (int i = 0; i != num; ++i)
{
cout << "ivec:\t" << ivec[i] << endl;
cout << "ipvec:\t" << *ipvec[i] << endl;
}
ivec: 0
*ipvec: -572662307
ivec: 1
*ipvec: -572662307
ivec: 2
*ipvec: 2
int num = 3;
vector<int> ivec;
vector<int*> ipvec;
for (int i = 0; i != num; ++i)
ivec.push_back(i);
for (int i = 0; i != num; ++i)
ipvec.push_back(&ivec[i]);
for (int i = 0; i != num; ++i)
{
cout << "ivec:\t" << ivec[i] << endl;
cout << "*ipvec:\t" << *ipvec[i] << endl;
}
ivec: 0
*ipvec: 0
ivec: 1
*ipvec: 1
ivec: 2
*ipvec: 2
Upvotes: 0
Views: 83
Reputation: 1403
So std::vector allocates memory in and resizes based off input. So in variation 1 you cross over the first allocation size (2 in this case). So your pointers for [0] and [1] are no longer valid since the array inside the vector has been reallocated and now has a different address. In variation 2 you don't have this problem since you have already allocated the full list of the vector, so all the pointers you add are valid. This is not an issue of scope, but instead from the fact std::vector allocates the internal grows the array by some constant factor (for example 2 so you have size 2 then 4 then 8 etc.) when the list is growing. ( hence why [2] works in both iterations (since the internal array is of size 4 at the end).
Upvotes: 4