How to define an alias to a pointer to an integer?

我的梦境 提交于 2021-01-29 07:57:47

问题


I am trying to run the following code, but I am getting the following error.

error: cannot declare pointer to 'int&'

#include <iostream>
using namespace std;

int main()
{
    int x = 5;
    int *ptr = &x;

    int &(*y) = ptr;
    *y = 5;

    cout << *ptr << endl;
    return 0;
}

回答1:


If you just want a new pointer to the same region of memory, use:

int *y = ptr;

This not so much an "alias" in that if you change *ptr or *y, both will change, but if you change the pointers themselves, the other will not be updated.

If you actually do want a reference to a pointer, use:

int *&y = ptr;



回答2:


You declare references to pointers the same way you declare references to basic types.

Consider:

int main()
{
    int i = 0; // int

    int& ir = i; // int reference (reference to int)

    int* ip = &i; // int pointer (pointer to int)

    int*& ipr = ip; // int pointer reference (reference to pointer to int)

    *ip = 5;

    cout << *ipr << endl;
    return 0;
}



回答3:


int *ptr = &x;

pointer value has an address and a type of x.

when you typed code above, the value of ptr is an address of x, and ptr know the type of x.

int * (&y) = ptr;

the code above is declaring variable 'y' (type:int*, define:ptr's reference)

reference variables should be declared and defined simultaneously.

anyway, as a result, ptr and y are pointing same memory address.

you can easily think y is a nickname of ptr.

so you can access the variable 'x' by using y, instead of ptr.




回答4:


v - a variable name.

&v - a variable that will be a reference of something.

*&v - a variable that will be a reference of a pointer to something

int *&v - a variable that will be a reference of a pointer to int

Or for a more interesting example,

(*&v)[5] - a variable that will be a reference of a pointer to an array of 5 something

int (*&v)[5] - a variable that will be a reference of a pointer to an array of 5 int



来源:https://stackoverflow.com/questions/29719404/how-to-define-an-alias-to-a-pointer-to-an-integer

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