In the following code, I get a different address every time for the first element of std::vector v. Why is it so?
#include <memory>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v;
for (int i=0; i<10; ++i)
{
int b = i;
v.push_back(b);
std::cout << std::addressof(v[0]) << std::endl;
}
return 0;
}
Output:
0x603010
0x603030
0x603010
0x603010
0x603050
0x603050
0x603050
0x603050
0x603080
0x603080
Because new memory may have to be allocated for the data contained in the vector when you call
v.push_back(b);
P.S.
You said:
In the following code, I get a different address every time for the first element of std::vector v. Why is it so?
If you look at your output, that is not true for every time :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With