Passing and Assigning New Value to Pointer C++

流过昼夜 提交于 2019-12-02 03:51:24

问题


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 returns. I'm not sure if this is possible, but I'd like to do:

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;
}

Is this possible, or will intPtr not maintain the new assignment after returning from foo? Could this work (if it doesn't: why)?


回答1:


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
}



回答2:


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;
}



回答3:


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; 
}


来源:https://stackoverflow.com/questions/28510101/passing-and-assigning-new-value-to-pointer-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!