0
請解釋下面的代碼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;
}
這是功課嗎? – ildjarn 2011-05-26 07:17:07
如果代碼中的註釋不清楚,應該閱讀「C++指針」。只是把它放在Gooogle – MajesticRa 2011-05-26 07:19:07
'ptr =(int *)(&x);'(後面加上'* ptr = 8')是未定義的行爲,詢問程序的行爲是沒有意義的 – GManNickG 2011-05-26 07:19:19