vector data

// vector::data paste bin link http://pastebin.com/p0Ddchn4
‪#‎include‬
#include
int main ()
{
std::vector 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;
}
why is output
myvector contains: 10 20 0 100 0
instead of
myvector contains: 10 20 100 0 0

The reason is the compiler when reads p[2] it takes *p as the first element.Hence as *p is currently the 2nd element and what you are overwriting is the address *(p+2)…the result is stored in 4th element.

//