Home > Blockchain >  What does this C pointer syntax mean?
What does this C pointer syntax mean?

Time:07-28

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?

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related