I found this in a final exam:
int a = 564;
int* pa = &a;
int *& pr = pa;
cout << *pr;
According to the multiple choice answer, the code is valid, and displays the value of a.
But I'm confused about evaluation and precedence for line 3. Order of operations for C states that * and & have the same order. So, would it then be int *(&pr)
? How can this be described in words?
Thank you.
The third line defines a pointer reference (or a reference to a pointer, if you want). Assigning it to a pointer makes pr
to actually be an alias to pa
, and when evaluated, it points where pa
points to, that is, a
.
In the declaration of a variable, *
and &
don't have the meaning of operators, so precedence doesn't make sense here.
It's a reference to a pointer. In C, you would express that as a pointer to a pointer.
You could write something like this:
// C++ style
void update_my_ptr(int*& ptr) { ptr = new int[1024]; }
// C style
void update_my_ptr_c(int **ptr) { *ptr = malloc(1024 * sizeof(int)); }
int main()
{
int *ptr;
update_my_ptr(ptr);
// Here ptr is allocated!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With