簡體   English   中英

C++ 指針混淆

[英]C++ Pointer Confusion

請解釋以下代碼

#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限定 object 的值。 一旦你有未定義的行為,任何事情都可能發生,並且無法推斷程序的行為。

由於x是一個const int ,編譯器很可能會在您使用x的地方直接替換您已初始化的值(在可能的情況下)。 所以你的源代碼中的行:

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

將在編譯時替換為:

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

這就是為什么您仍然看到 10 打印出來的原因。

但正如查爾斯解釋的那樣,行為是未定義的,所以像這樣的代碼可能會發生任何事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM