Person.Junkie
Person.Junkie

Reputation: 1886

C++ vector.begin() and vector[0]

why this two line prints different addresses?

vector<int> v1{ 12,2,34 };
printf_s("%d -  0x%p\n", v1[0], &v1[0]);
printf_s("%d -  0x%p\n",*v1.begin(), v1.begin());

Values in this addresses are same but address itself is different. Does it mean that there is two copy of the same array?

EDIT: In debug mode it prints different addresses, in release mode there are same addresses :)

Upvotes: 0

Views: 5933

Answers (2)

SHAHS
SHAHS

Reputation: 472

for a vector object v1:

&V[0] is the the address of first element of the object v1.

when we create an iterator e.g vector<>::iterator iter the iter itself is an other object as explain in this document.

Iterator: a pointer-like object that can be incremented with ++, dereferenced with *, and compared against another iterator with !=.

I hope this reference manual answer your question in detail.

Upvotes: 2

Vittorio Romeo
Vittorio Romeo

Reputation: 93324

v1.begin() returns an std::vector<int>::iterator, which is not necessarily an address to v1[0]. In fact, attempting to print it out using printf gives me a warning:

warning: format '%p' expects argument of type 'void*', but argument 3 has type 'std::vector::iterator`

Unless you're sure that in your particular Standard Library implementation and with your current compilation options std::vector<int>::iterator is an alias for int*, the comparison is meaningless.

Upvotes: 10

Related Questions