C++ pointer to pointer and pointer to reference

Show me using a pointer to a pointer and a reference to a pointer to modify a pointer passed to a method to make better use of it. (The pointer to the pointer mentioned here is not a two-dimensional array)

why you need to use them

When we pass a pointer as a parameter to a method, we actually pass a copy of the pointer to the method. It can also be said that passing a pointer is a pointer-by-value transfer.

If we modify the pointer inside the method, there will be problems. The modification in the method is only a copy of the modified pointer, not the pointer itself. The original pointer still retains the original

value of . Let's illustrate the problem with the following code:

copy code
int m_value = 1;

void func(int *p)
{
    p = &m_value;
}

int main(int argc, char *argv[])
{
    int n = 2;
    int *pn = &n;
    cout << *pn << endl;
    func(pn);
    cout << *pn <<endl;
    return 0;
}
copy code

Take a look at the output

The output is two 2

pointers using pointers

Demonstrate using a pointer to a pointer as a parameter

copy code
void func(int **p)
{
    *p = &m_value;

    // You can also allocate memory according to your needs 
    *p = new  int ;
     **p = 5 ;
}

int main(int argc, char *argv[])
{
    int n = 2;
    int *pn = &n;
    cout << *pn << endl;
    func(&pn);
    cout << *pn <<endl;
    return 0;
}
copy code

Let's take a look at the method func(int **p)

  • p:   is a pointer to a pointer, we will not modify it here, otherwise the pointer address pointed to by this pointer will be lost
  • *p:  是被指向的指针,是一个地址。如果我们修改它,修改的是被指向的指针的内容。换句话说,我们修改的是main()方法里 *pn指针
  • **p: 两次解引用是指向main()方法里*pn的内容

指针的引用

再看一下指针的引用代码

copy code
int m_value = 1;

void func(int *&p)
{
    p = &m_value;

    // 也可以根据你的需求分配内存
    p = new int;
    *p = 5;
}

int main(int argc, char *argv[])
{
    int n = 2;
    int *pn = &n;
    cout << *pn << endl;
    func(pn);
    cout << *pn <<endl;
    return 0;
}
copy code

Take a look at the func(int *&p) method

  • p: is a reference to a pointer, *pn in the main() method
  • *p: is the content pointed to by pn in the main() method.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326662348&siteId=291194637