Search code examples
c++pointersreferencedereference

Why changes the '&' character the output for these two codes?


First code:

int a = 1;

void func(int* ptr) {
    ptr = &a;
}

int main() {
    int nvar = 2;
    int* pvar = &nvar;
    func(pvar);
    std::cout << *pvar;
}
//Output: 2

Second code:

int a = 1;

void func(int*& ptr) {
    ptr = &a;
}

int main() {
    int nvar = 2;
    int* pvar = &nvar;
    func(pvar);
    std::cout << *pvar;
}
//Output: 1

The only difference is the '&' character in the 'func' function. But can someone explain me, what it does in this situation?


Solution

  • I know what it does, but in the second code it is combined with * , and I dont know what this combination means

    T& denotes "reference to T".

    Now replace T with whatever you like. Eg for pointer to int, T==int* we have int*& which is a reference to a pointer to int.

    It is no different to passing non-pointers to functions as references. When ptr is passed by value then func works on a copy, when passed by reference func works on the instance passed in.