Search code examples
c++pointersstdvector

Accessing elements with std::vector::data()


For this piece of code I am using the data() method of the vector to access its elements:

#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector (5);

  int* p = myvector.data();

  *p = 10;
  ++p;
  *p = 20;
  p[2] = 100;

  std::cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size(); ++i)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}

Which generates

myvector contains: 10 20 0 100 0

The question is why p[2] is 0? Assuming myvector.data() is a pointer to the first element (index 0), then p[0] is 10 which fine. ++p points to the next element which is p[1] and that is 20 which is also fine. Now, p[2] is the next element after p[1]. So, the sequence should be 10 20 100. Whats is the mistake here?


Solution

  • You incremented p by 1 and then wrote into p[2], which effectively now is myvector[3].

    Writing to p[1] would write to the field adjacent to *p.