为什么存储整数的内存块的值会重复变化?

时间:2013-08-29 02:51:37

标签: c++ pointers point

首先,我定义了一个整数指针和类A。我想传递一个指向A方法的指针来存储它。

当我调用A的方法时,我发现类A的整数成员总是会改变。

我对如何避免这些变化感到困惑。

#include <IOSTREAM>

using namespace std;

class   A
{
private:
   int* a;
public:
   A()
   {

   };
   ~A()
   {

   };

void setA(int n)
{
    cout << "n == " << n << "&n == " << &n << endl;
    a = &n;
    cout << "now a== " << a << endl;
}

void PassA(int* &outint)
{
    cout << "a == " << a <<  "  *a == " << *a <<endl;
    outint = a;
    cout << "outint = " << outint << endl;
}

void Print()
{
    cout << "a ==================== " << a << endl;
    cout << "*a ==================== " << *a << endl;
}
};

int main()
{
A A_1;
int num = 5;
    A_1.setA(num);

    int *intb= NULL ;
    A_1.PassA(intb);
    //When the line above done,the value of A_1.a will change.
    cout << "intb ==  " << intb << endl;
    cout << "*intb =="  << *intb << endl;
    cout << "num ==" << num << endl;
A_1.Print();
return 0;
}

输出:

n == 5&n == 0x28fe90
now a== 0x28fe90
a == 0x28fe90  *a == 2686708
outint = 0x28fe90
intb ==  0x28fe90
*intb ==4619604
num ==5
a ==================== 0x28fe90
*a ==================== 4619604

1 个答案:

答案 0 :(得分:1)

您正在将内存位置设置为堆栈中的值。方法结束时,将丢弃堆栈值。如果您必须分配自己的内存,请使用new并删除:

void setA(int n)
{
    cout << "n == " << n << "&n will be different every time" << endl;
    a = new int();
    *a = n;
    cout << "now a== " << a << endl;
}

或者,如果要在被调用者中使用变量的实际地址,则需要传入int指针而不是int:

void setA(int* n)
{
    cout << "n == " << *n << " &n = " << n << endl;
    a = n;
    cout << "now a== " << a << endl;
}