0
votes

Say datais a direct pointer to the memory array used by a vector.

What then, does &data[index] mean?

I'm guessing data[index] is a pointer to the particular element of the array at position index, but then is &data[index]the address of that pointer?

3
If data points at the "memory array used by a vector", it points at the first element of that vector. data[index] is then (a reference to NOT a pointer to) the indexth element of the vector with zero-based indexing (e.g. if index is 0 then data[index] is the first element of the vector, if index is 9 then data[index] is the tenth element of the vector). The preceding assumes the vector has ten or more elements - if that assumption is untrue, then evaluating the expression data[index] gives undefined behaviour. &data[index] is the address of data[index]. - Peter
Your guess is wrong. data[index] is the element at position index, not a pointer to it. &data[index] is the pointer. - john

3 Answers

1
votes

Start with working out the types.

Suppose data is a T*; a pointer to the first element of an array of T.
Then data[index] is a T, and that T is an element of the array.
And since data[index] is a T, &data[index] is a T*; it is a pointer to the array element data[index].

Also, if data is a pointer, data[index] is equivalent to *(data + index), so &data[index] is equivalent to &*(data + index), and the &* cancel each other out and you're left with &data[index] == data + index.

0
votes

&x is the address of x. x can be the element in an array. If data is a vectors data() (a pointer to first element of the vectors internal array) then data[index] is the element at index index of that vector.

Yes, &data[index] is a pointer to element at index index of the vector.

0
votes

The subscript operator[] has higher precedence than the address of operator&. Thus, due to operator precedence &data[index] is equivalent to(grouped as):

&(data[index]) //this is equivalent to the expression &data[index]

which means that the above is a pointer to an element at index index of the array. This is because data[index] gives us the element at index index so applying the address of operator & will give us a pointer to that element.