C ++指针混乱
|
请说明以下代码
#include <iostream>
using namespace std;
int main()
{
const int x = 10;
int * ptr;
ptr = (int *)( &x ); //make the pointer to constant int*
*ptr = 8; //change the value of the constant using the pointer.
//here is the real surprising part
cout<<\"x: \"<<x<<endl; //prints 10, means value is not changed
cout<<\"*ptr: \"<<*ptr<<endl; //prints 8, means value is changed
cout<<\"ptr: \"<<(int)ptr<<endl; //prints some address lets say 0xfadc02
cout<<\"&x: \"<<(int)&x<<endl; //prints the same address, i.e. 0xfadc02
//This means that x resides at the same location ptr points to yet
//two different values are printed, I cant understand this.
return 0;
}
没有找到相关结果
已邀请:
2 个回复
破弯
这行导致未定义的行为,因为您正在修改
合格对象的值。一旦您具有未定义的行为,任何事情都可能发生,并且不可能推理程序的行为。
慷祈霖黑
是
,因此编译器很可能会在您使用
的地方直接替换您初始化时使用的值(如果可能)。因此,您的源代码行如下:
将在编译时替换为:
这就是为什么您仍然看到10张纸的原因。 但是正如Charles解释的那样,该行为是不确定的,因此此类代码可能会发生任何事情。