Can someone help me understand this? int *& pr [duplicate]

送分小仙女□ 提交于 2020-02-02 04:59:27

问题


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.


回答1:


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!

}



回答2:


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.




回答3:


Line three creates a reference (read: alias) of a pointer to an int. If you were to set pr to 0, pa would also be equal to 0 (and vice-versa).



来源:https://stackoverflow.com/questions/4424793/can-someone-help-me-understand-this-int-pr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!