3

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
Shibli
  • 5,879
  • 13
  • 62
  • 126
  • Now do you understand why [I said](https://stackoverflow.com/questions/24345183/comparing-stdaddressof-with-hexadecimal-number#comment37638310_24345183) comparing the address of the elements to a numeric value is useless? – Praetorian Jun 21 '14 at 23:05
  • Reallocation has been discussed numerous times already – SwiftMango Jun 22 '14 at 18:35

2 Answers2

8

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

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Yes, whenever the value returned from `capacity` function has changed, the data is stored in a new memory location. – Neil Kirk Jun 21 '14 at 22:36
  • @Shibli Note you can `reserve` capacity for your vector so that it won't need to be resized when calling push_back: http://www.cplusplus.com/reference/vector/vector/reserve/ – Matt Coubrough Jun 21 '14 at 23:02
0

Right, you don't want to get/use/save the address of an element of a vector (typically unless you don't insert/erase between pointer access and usage, but ideally never, just use the index!). While the vector would maintain contiguous guarantees, it is free to reallocate the elements at larger contiguous memory blocks to accommodate increasing capacity requirements. This isn't, obviously, the case for say a linked list, which doesn't require contiguous memory. And btw, vector iterators face the same "invalidated on insert/delete" concern as pointers to elements.

Aloo
  • 1