指向地址结构错误CDCDCD的c++结构指针

c++ struct pointer to adress struct error CDCDCD

本文关键字:结构 c++ 指针 CDCDCD 错误 地址      更新时间:2024-05-09
struct XYZ {
XYZ *adress;
};
XYZ *Ex;
int main() {
Ex = new XYZ[3];
Ex->adress = (++Ex);
cout << Ex->adress << endl;
Ex->adress = (++Ex);
cout << Ex->adress << endl;
Ex->adress = (--Ex)->adress;
cout << Ex->adress << endl;    

输出:

0105E4240105E4280105E424
struct XYZ {
XYZ *adress;
};
XYZ *Ex;
void copy_adress(XYZ *Ex) {
Ex->adress = (++Ex);
}
int main() {
Ex = new XYZ[3];
copy_adress(Ex);
cout << Ex->adress << endl;
Ex->adress = (++Ex);
cout << Ex->adress << endl;
Ex->adress = (--Ex)->adress;
cout << Ex->adress << endl;

输出:

CDCDCDCD00A3E53CCDCDCD

你能告诉我为什么会发生这种情况,以及我如何修复它吗?

当您复制指针或将其传递给函数时,指针的行为就像常规对象一样。对副本的更改不会反映在原件中。要使函数中的更改可见,您需要引用它:

void copy_adress(XYZ *&Ex) {
Ex->adress = (++Ex);
}

现在,这两个版本是等效的。

(这是补充信息,cigien回答了主要问题(

关于CCD_ 1的测序,评论中有一些猜测。由于C++17,=的右操作数在左操作数之前排序。由于C++11,两个操作数都在赋值前排序。

因此++Ex被完成,然后Ex的新值被用于计算Ex->address。在C++17之前,这是未定义的行为。

第二个代码示例确实有UB,但原因不同:读取未初始化的内存: