C++ C++;指针混淆
请解释以下代码C++ C++;指针混淆,c++,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 po
#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;
}
#包括
使用名称空间std;
int main()
{
常数int x=10;
int*ptr;
ptr=(int*)(&x);//使指针指向常量int*
*ptr=8;//使用指针更改常量的值。
//这是真正令人惊讶的部分
库特
这一行会导致未定义的行为,因为您正在修改常量
限定对象的值。一旦您有未定义的行为,任何事情都可能发生,并且无法对程序的行为进行推理。因为x
是常量
,编译器很可能会在您使用x
,直接替换已初始化的值(如果可能)。因此,源代码中的行:
cout<<"x: "<<x<<endl;
coutIf如果代码中的注释不清楚,您应该阅读关于“C++指针”的内容。只需将其放入Googleptr=(int*)(&x);
(后跟*ptr=8
)是未定义的行为,询问程序的行为是没有意义的。@GMan:不是那一行有未定义的行为,而是下一行尝试写入常量限定对象。请参阅参考。您想解释的代码是什么?g++会像它应该的那样抛出错误。
cout<<"x: "<<x<<endl;
cout<<"x: "<<10<<endl;