Dereferencing operator

closed account (G1vDizwU)
Hello all,

Whet is the difference between 1) and 2) and what will be the values of them:

1
2
1) double h = (*Jill_data)[5];
2) double h = *Jill_data[5];

when we have a vector<double>* Jill_data with the data: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}?


And also Whet is the difference between 3) and 4) please?
1
2
3) double* dh = &(*Jill_data)[5];
4) double* dh = Jill_data[5]
Last edited on
1) Valid. Dereference pointer to vector and assign sixth element to double.
Same as saying Jill_data->at(5);

2) Invalid. Attempting to index into pointer and deference result. Pointer types don't have [] overloads.

3) Valid. Dereference pointer to vector and assign address of sixth element to pointer.
Same as saying &Jill_data->at(5);

4) Invalid. Attempting to index into pointer and deference result. Pointer types don't have [] overloads.

Running example: https://ideone.com/SSXdVW
Operator precedence: http://en.cppreference.com/w/cpp/language/operator_precedence
Last edited on
@MrHutch

Um... isn't ptr[n] just the same as *(ptr + n) ? In other words, you can use array index syntax as an alternative to pointer arithmetic. You may well end up accidentally looking at invalid memory, but it's legal C++.

@Tomfranky:

So:

1) As MrHutch says, this dereferences the pointer to the vector, and assigns the 6th element to h.

2) This is equivalent to *(Jill_data[5]). In other words, this treats Jill_data as if it were an array of vector<double>, so it accesses the memory at the address given by Jill_data + 5. The statement is still illegal C++, because Jill_data[5] is of type vector<double>, so it can't be dereferenced.

3) Again, this is as MrHutch says.

4) Illegal C++, for similar reasons to 2. Jill_data[5] evaluates to a vector<double>, and this can't be assigned to a double*.
Last edited on
@MikeyBoy

Yep, you're absolutely correct. Brainfart.

Easily done :)
closed account (G1vDizwU)
Thanks to you two very much. :)
You're welcome!
Topic archived. No new replies allowed.