Xavier
Xavier

Reputation: 9049

How does a pointer to a vector work?

If I have the following:

vector<int> v(4,0);
vector<int>* p = &v;
int element = p[0];

Will element be the same value as v[0]? I'm getting confused here about the [] operator.

Upvotes: 0

Views: 219

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 476950

Short answer: no.

What you have is not even valid C++. p[0] is the same as *p, which is of type vector<int> and thus not convertible to int.

The []-notation merely suggests that you think of p as an array of vectors, and you are accessing the array's first element, which is v. More generally, for any pointer p, the notation p[k] is identical to *(p + k) (in fact to a fault, as you can say a[5] and 5[a] interchangeably).

So if you really wanted to, you could write p[0][i] for the ith element of the vector, though it is more customary to just write (*p)[i] (parentheses needed for the correct precedence).


When I first skimmed over the question, I thought you might be looking for some clever hack and wanted to know whether **(int**)(p) was equal to v[0]. That is indeed plausible, as the first element of the vector's data structure is often the pointer to the vector's internal buffer. Don't use this at home.

Upvotes: 8

CapelliC
CapelliC

Reputation: 60004

No, p it's a pointer to the vector, not the content! If you try to compile, you get something like

error: cannot convert ‘std::vector<int>’ to ‘int’ in initialization

from your compiler. Use (*p)[0] to get the value.

Upvotes: 4

ruakh
ruakh

Reputation: 183241

For any pointer p, p[0] is the same as *p. (More generally, p[i] is a special notation for *(p+i). Fun fact: you can also write i[p], because *(p+i) == *(i+p). C and C++ are weird like that.) So in your case, where p is a pointer to v, you're essentially writing int element = v;. It won't work, because the right-hand-side is a vector.

Upvotes: 6

Related Questions