如何解决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;
}
解决方法
*ptr = 8;
这行导致未定义的行为,因为您正在修改const
合格对象的值。一旦您具有未定义的行为,任何事情都可能发生,并且不可能推理程序的行为。
,由于x
是const int
,因此编译器很可能会在您使用x
的地方直接替换您初始化时使用的值(如果可能)。因此,您的源代码行如下:
cout<<\"x: \"<<x<<endl;
将在编译时替换为:
cout<<\"x: \"<<10<<endl;
这就是为什么您仍然看到10张纸的原因。
但是正如Charles解释的那样,该行为是不确定的,因此此类代码可能会发生任何事情。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。