Passing and Assigning New Value to Pointer C++

前端 未结 3 908
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
    }
    
    0 讨论(0)
  • 2021-01-21 13:06

    Pass a pointer of the pointer and assign to it

    int main()
    {
        int i = 100, j = 200;
        int * intPtr = &i;
        foo( &intPtr, j );
        //  I want intPtr to point to j, which contains 200 after returning from foo.
    }
    
    void foo( int ** fooPtr, int & newInt )
    {
        int * newIntPtr = newInt;
        *fooPtr = newIntPtr;
    }
    
    0 讨论(0)
  • 2021-01-21 13:09

    If you programing in pure C you can do like this

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void foo(int **, int *);
    
    
     int main()
    {
      int i = 100, j = 200;
      int * intPtr = &i;
      int  *intPtr2=&j;
      foo( &intPtr, intPtr2 );
      //  I want intPtr to point to j, which contains 200 after returning   from foo.
      printf("%d",*intPtr);
    }
     void foo( int ** fooPtr, int * newInt )
    {
      int * newIntPtr = newInt;
    
      *fooPtr = newIntPtr; 
    }
    
    0 讨论(0)
提交回复
热议问题