Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting different address every time

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
like image 901
Shibli Avatar asked Jan 20 '26 17:01

Shibli


1 Answers

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 :)

like image 70
R Sahu Avatar answered Jan 22 '26 07:01

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!