相关疑难解决方法(0)

通过非const指针修改const

我对以下代码中发生的事情感到有点困惑:


const int e = 2;

int* w = ( int* ) &e;          // (1) cast to remove const-ness
*w = 5;                        // (2)

cout << *w << endl;            // (3) outputs 5
cout << e << endl;             // (4) outputs 2

cout << "w = " << w << endl;   // (5) w points to the address of e
cout << "&e = " << &e << endl;
Run Code Online (Sandbox Code Playgroud)

在(1)中,w指向e的地址.在(2)中,该值变为5.但是,当显示*w和e的值时,它们的值不同.但是如果你打印w指针和&e的值,它们具有相同的值/地址.

为什么e仍然包含2,即使它被改为5?他们存放在一个单独的位置?还是暂时的?但是,为什么w指出的价值仍然是e的地址?

c++ pointers casting const-correctness

13
推荐指数
2
解决办法
1021
查看次数

将const int转换为指针?

可能重复:
通过非const指针修改const

我有以下代码:

const int x = 5;
int *p = (int*)&x;

*p = 2; // Line 1

cout << x << " - " << *p << endl;
cout << &x << " - " << p << endl;
Run Code Online (Sandbox Code Playgroud)

并得到了结果:

5 - 2
0012FF28 - 0012FF28
Run Code Online (Sandbox Code Playgroud)

我知道代码很奇怪,不应该这样做.但我想知道为什么相同的地址但得到不同的结果?哪个Line 1商店2号?

c++ pointers casting

0
推荐指数
1
解决办法
272
查看次数

标签 统计

c++ ×2

casting ×2

pointers ×2

const-correctness ×1