#include <iostream>
int main()
{
const int i=10;
int *p =(int *) &i;
*p = 5;
cout<<&i<<" "<<p<<"\n";
cout<<i<<" "<<*p;
return 0;
}
输出:
0x22ff44 0x22ff44
10 5
请解释。
最佳答案
好吧,您的代码显然包含未定义的行为,所以任何事情都有可能发生。
在这种情况下,我相信会发生这样的事情:
在 C++ 中,const int 被认为是编译时常量。在您的示例中,编译器基本上将您的“i”替换为数字 10。
关于c++ - 意外的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5324685/