相关疑难解决方法(0)

201
推荐指数
6
解决办法
6万
查看次数

相同内存地址的两个不同值

#include <iostream>
using namespace std;

int main() {
    const int N = 22;
    int * pN = const_cast<int*>(&N);
    *pN = 33;
    cout << N << '\t' << &N << endl;
    cout << *pN << '\t' << pN << endl;
}
Run Code Online (Sandbox Code Playgroud)

产量

22 0x22ff74

33 0x22ff74

为什么同一地址有两个不同的值?

c++

16
推荐指数
3
解决办法
1740
查看次数

const_cast 不会改变值

之后const_cast,主函数中的值不会改变。但是当调用外部函数时发生变化,仍然在 main 中打印旧值(const int首先初始化的地方)。

int main() {
    const int i = 5;
    int* p = const_cast<int*>(&i);
    *p = 22;
    std::cout<<i;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是5,为什么?观察窗口显示的值i = 22

观察窗口值

那么为什么它会打印 5 呢?如果我调用外部函数,输出会有所不同:

void ChangeValue(const int i) {
    int* p = const_cast<int*>(&i);
    *p = 22;
    std::cout<<i; //Here the value changes to 22
}

int main() {
    const int i = 5;
    ChangeValue(i); //Value changes to 22 in the ChangeValue function
    std::cout<<i // It again prints 5. …
Run Code Online (Sandbox Code Playgroud)

c++

2
推荐指数
1
解决办法
566
查看次数

标签 统计

c++ ×3

c++-faq ×1

undefined ×1

undefined-behavior ×1