传递和赋值指针C ++的新值 [英] Passing and Assigning New Value to Pointer C++

查看:135
本文介绍了传递和赋值指针C ++的新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我传递一个指向函数的指针。我想为函数中传递的指针指定一个新的地址,我想在函数返回后使用该地址。我不知道这是否可能,但我想做:

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

这是可能的,否则 intPtr foo 返回后不保留新的赋值语句?可以这项工作(如果它不:为什么)?

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

推荐答案

传递指针的引用:

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

/ em>工作是你传递指针 by-value 。传递by-value会在函数中创建一个临时变量,所以一旦函数返回,临时变量就会消失。

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.

没有什么不同: / p>

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
}

c $ c> a 通过值传递,因此 foo()函数将参数更改为 10 在函数内。但是,在函数返回后,您将看到 中的 a 不会更改为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.

要更改 a ,需要传递 int 通过引用:

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
}

这篇关于传递和赋值指针C ++的新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆