代码改变世界

为何地址一样,值却不一样?

2012-05-02 12:28  Rollen Holt  阅读(631)  评论(1编辑  收藏  举报

先看代码:

#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    const  int a = 1;
    int *p = const_cast<int*>(&a);
    *p = 2;

    cout << "value a="<< a << endl;
    cout << "value *p=" <<*p << endl;
    cout << "address a=" <<&a << endl;
    cout << "address p=" <<p << endl;

    return 0;
}

输出结果:

value a=1
value *p=2
address a=0022FBC8
address p=0022FBC8
请按任意键继续. . .

采用volatile关键字,修改为:

#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    const volatile int a = 1;
    int *p = const_cast<int*>(&a);
    *p = 2;

    cout << "value a="<< a << endl;
    cout << "value *p=" <<*p << endl;
    cout << "address a=" <<&a << endl;
    cout << "address p=" <<p << endl;


    return 0;
}

结果为:

value a=2
value *p=2
address a=1
address p=0042FDB8
请按任意键继续. . .