简体   繁体   English

C ++指针引用混乱

[英]c++ pointer reference confusion

    struct leaf
    {
        int data;
        leaf *l;
        leaf *r;
    };
    struct leaf *p;


void tree::findparent(int n,int &found,leaf *&parent)

This is piece of code of BST. 这是BST的代码。 I want to ask. 我想问问。 why 为什么

 leaf *&parent

Why we need "reference mark" here? 为什么在这里需要“参考标记”?

parent is also a leaf, why can't I just use leaf* parent ? parent也是叶子,为什么我不能只使用leaf* parent

code below for your reference. 以下代码供您参考。 Thank you! 谢谢!

void tree::findparent(int n,int &found,leaf *&parent)
{
    leaf *q;
    found=NO;
    parent=NULL;

    if(p==NULL)
        return;

    q=p;
    while(q!=NULL)
    {
        if(q->data==n)
        {
            found=YES;
            return;
        }
        if(q->data>n)
        {
            parent=q;
            q=q->l;
        }
        else
        {
            parent=q;
            q=q->r;
        }
    }
}

You are passing the pointer parent in by reference , so that you can modify that pointer: 您正在通过reference传递指针的parent ,以便可以修改该指针:

parent=q;

If you passed the pointer in by value , the modifications would be to a copy of the pointer that expires at the end of the function. 如果按值传递了指针,则修改将是在函数末尾到期的指针的副本。

When you use REFERENCE TO POINTER, you can change the value of the pointer. 使用REFERENCE TO POINTER时,可以更改指针的值。 You may need to use this schema in link list implementation to change the head of the list. 您可能需要在链接列表实现中使用此架构来更改列表的开头。

void passPointer(int *variable)
{
    *variable = (*variable)*2;
    variable = NULL; // THIS CHANGES THE LOCAL COPY NOT THE ACTUAL POINTER
}
void passPointerReference(int* &variable)
{
    *variable = (*variable)*3;
    variable = NULL; // THIS CHANGES THE ACTUAL POINTER!!!!
}
int main()
{    
    int *pointer;
    pointer = new int;
    *pointer = 5;
    passPointer(pointer);
    cout << *pointer; // PRINTS 10
    passPointerReference(pointer);
    cout << *pointer; // GIVES ERROR BECAUSE VALUE OF pointer IS NOW 0.
    // The constant NULL is actually the number 0.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM