繁体   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