2011-05-26 118 views
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; 
} 
+1

這是功課嗎? – ildjarn 2011-05-26 07:17:07

+0

如果代碼中的註釋不清楚,應該閱讀「C++指針」。只是把它放在Gooogle – MajesticRa 2011-05-26 07:19:07

+2

'ptr =(int *)(&x);'(後面加上'* ptr = 8')是未定義的行爲,詢問程序的行爲是沒有意義的 – GManNickG 2011-05-26 07:19:19

回答

11
*ptr = 8; 

此行導致未定義行爲因爲要修改const限定對象的值。一旦你有未定義的行爲任何事情都可能發生,並且不可能推斷程序的行爲。

6

由於xconst int,編譯器很可能會在您使用x的地方直接替換已初始化的值(如果可能)。因此,在你的源代碼行:

cout<<"x: "<<x<<endl; 

將這個在編譯的時候進行更換:

cout<<"x: "<<10<<endl; 

這就是爲什麼你仍然可以看到10打印。

但正如Charles解釋的那樣,行爲是不確定的,所以任何事情都可能發生在像這樣的代碼上。