C++ 通过作为参数传递的指针更改 int 变量的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32533514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:10:09  来源:igfitidea点击:

Changing the value of a int variable through pointers passed as arguments?

c++pointers

提问by the_naive

I want to modify values of some variables of a particular class by accessing address of these variables from another different class through a function. So, to access this address I try to pass pointers-to-variables as arguments to a function, where these pointers-to-variables will be set with the address of the variables. To learn how to do it, I'm trying to mimic in a simple program.

我想通过函数访问来自另一个不同类的这些变量的地址来修改特定类的某些变量的值。因此,为了访问这个地址,我尝试将变量指针作为参数传递给函数,在函数中,这些变量指针将使用变量的地址进行设置。为了学习如何做到这一点,我试图模仿一个简单的程序。

Here is my code:

这是我的代码:

#include <iostream>    

using namespace std;
int numberA = 100;
int numberB = 200;

void referenceSetter(int *a, int *b)
{
    *a = numberA;
    *b = numberB;
}

void numberOutput()
{
    cout << "A = " << numberA << endl;
    cout << "B = " << numberB << endl;
}

int main() {

    int *testA = 0; 
    int *testB = 0;
    referenceSetter(testA, testB);

    *testA = 30;
    *testB = 40;
    numberOutput();

    return 0;
}

As you could see I declare numberAand numberBas global variables and set their values. The I try to get the address of these two variables through the function referenceSetterfunction and then after that I try to modify the values in those variables using the references. Apparently, I'm doing something wrong which leads to to have Unhandled Exceptionerror exactly when I try to modify the values and try to set them as 30 and 40 resepectively.

如您所见,我将numberA和声明numberB为全局变量并设置它们的值。我尝试通过函数referenceSetter函数获取这两个变量的地址,然后尝试使用引用修改这些变量中的值。显然,Unhandled Exception当我尝试修改值并尝试分别将它们设置为 30 和 40 时,我做错了导致错误。

Alternatively I tried the following approach:

或者,我尝试了以下方法:

#include <iostream>    

    using namespace std;
    int numberA = 100;
    int numberB = 200;

    void referenceSetter(int *a, int *b)
    {
        a = &numberA;
        b = &numberB;
    }

    void numberOutput()
    {
        cout << "A = " << numberA << endl;
        cout << "B = " << numberB << endl;
    }

    int main() {

        int *testA; 
        int *testB;
        referenceSetter(testA, testB);

        *testA = 30;
        *testB = 40;
        numberOutput();

        return 0;
    }

But this approach throws up the error uninitialized local variables testA and testB. Do I have to initialize pointers too?

但是这种方法会引发错误uninitialized local variables testA and testB。我也必须初始化指针吗?

Please help me find my mistake. Thanks.

请帮我找出我的错误。谢谢。

采纳答案by Peter

The thing you're not understanding is that pointers are passed by value, just like any other variable. If you want the passed pointer to be changed, you need to pass a pointer to a pointer (or a reference to a pointer, but I'll leave that alone, as explaining references at this point will confuse you further).

您不理解的是,指针是按值传递的,就像任何其他变量一样。如果您希望更改传递的指针,则需要传递指向指针的指针(或指向指针的引用,但我不会管它,因为此时解释引用会使您更加困惑)。

Your main()is passing NULL pointers to referenceSetter(). The assignment *a = numberAcopies the value of numberA(i.e. 100) into the memory pointed to by a. Since ais a NULL pointer, that has the effect of overwriting memory that doesn't exist as far as your program is concerned. The result of that is undefined behaviour which means - according to the standard - that anything is allowed to happen. With your implementation, that is triggering an unhandled exception, probably because your host operating system is detecting that your program is writing to memory that it is not permitted to write to.

main()正在将 NULL 指针传递给referenceSetter(). 赋值*a = numberAnumberA(ie 100)的值复制到 指向的内存中a。由于a是一个 NULL 指针,它具有覆盖就您的程序而言不存在的内存的效果。其结果是未定义的行为,这意味着 - 根据标准 - 任何事情都可以发生。对于您的实现,这会触发未处理的异常,可能是因为您的主机操作系统检测到您的程序正在写入不允许写入的内存。

If, after the call of referenceSetter()you want testAand testBto contain the addresses of numberAand numberBrespectively, you need to change referenceSetter()to something like;

如果在调用后的referenceSetter()你想testAtestB包含的地址numberAnumberB分别,你需要改变referenceSetter()的东西等;

void referenceSetter(int **a, int **b)
{
    *a = &numberA;
    *b = &numberB;
}

This allows the values passed to be addresses of pointers. *athen becomes a reference to the pointer passed. &numberAcompute the address of numberA, rather than accessing its value 100. Similarly for numberB.

这允许传递的值是指针的地址。 *a然后成为对传递的指针的引用。 &numberA计算 的地址numberA,而不是访问其值100。对于numberB.

The second change is to change main()so it calls the function correctly;

第二个更改是更改main()以便正确调用函数;

referenceSetter(&testA, &testB);

which passes the address of testA(and testB) to the function, so those pointers can be changed

它将testA(and testB)的地址传递给函数,因此可以更改这些指针

回答by alesegdia

You are trying to set the contents of address 0to be equal to the other numbers, so when you're doing *a = numberAyou're assigning a value of numberAto memory address 0.

您正在尝试将 address 的内容设置0为等于其他数字,因此当您这样做时,您正在为 memory address*a = numberA分配一个值。numberA0

Not sure, but I think what you're trying to achieve is this:

不确定,但我认为您想要实现的是:

#include <iostream>    

using namespace std;
int numberA = 100;
int numberB = 200;

void referenceSetter(int **a, int **b)
{
    *a = &numberA;
    *b = &numberB;
}

void numberOutput()
{
    cout << "A = " << numberA << endl;
    cout << "B = " << numberB << endl;
}

int main() {

    int *testA = 0;
    int *testB = 0;
    referenceSetter(&testA, &testB);
    *testA = 30;
    *testB = 40;
    numberOutput();
    return 0;
}

This way, using pointers to pointers as arguments for referenceSetter(), you are actually modifying the address that your passed pointers are pointing to.

这样,使用指向指针的指针作为 的参数referenceSetter(),您实际上是在修改传递的指针指向的地址。

回答by David C. Rankin

You are close, but the key is you need to pass the address ofthe value you want to set. You declare the values as intin mainand pass the address by using the &operator:

你已经接近了,但关键是你需要传递你想要设置的值的地址。您将值声明为intinmain并使用&运算符传递地址:

int *testA = 0;
int *testB = 0;
referenceSetter(&testA, &testB);

*testA = 30;
*testB = 40;
numberOutput();

If you declare testAand testBas pointers in mainand pass the pointer, the function gets a copy of the pointerinstead of the address of the valueyou want to set.

如果您将testA和声明testB为指针main并传递指针,则该函数将获得指针的副本,而不是您要设置的值地址