Varun Jain
Varun Jain

Reputation: 13

What does this C++ pointer syntax mean?

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?

Upvotes: 0

Views: 98

Answers (3)

molbdnilo
molbdnilo

Reputation: 66459

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.

Upvotes: 3

Alan
Alan

Reputation: 1

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.

Upvotes: 1

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123450

&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.

Upvotes: 1

Related Questions