Passing and Assigning New Value to Pointer C++

前端 未结 3 909
Happy的楠姐
Happy的楠姐 2021-01-21 12:48

I\'m passing a pointer to a function. I\'d like to assign a new address to the passed pointer inside the function, and I\'d like that address to be used after the function retu

3条回答
  •  甜味超标
    2021-01-21 13:03

    Pass a reference to the pointer:

    void foo( int *& fooPtr, int & newInt )

    The reason why your method does not work is that you're passing the pointer by-value. Passing by-value creates a temporary within the function, so as soon as the function returns, any changes to the temporary go away.

    It is no different than this:

    void foo(int x)
    {
       x = 10;
    }
    
    int main()
    {
       int a = 0;
       foo( a );
       // a is still 0, not 10
    }
    

    The a is passed by value, so the foo() function changes the parameter to 10 within the function. However, you will see that a in main does not change to 10 after the function returns.

    To change a, you need to pass the int by reference:

    void foo(int& x)
    {
       x = 10;
    }
    
    int main()
    {
       int a = 0;
       foo( a );
       // a is now 10
    }
    

提交回复
热议问题