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;
Output:
0105E424 0105E428 0105E424
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;
Output:
CDCDCDCD 00A3E53C CDCDCDCD
Can you tell me why this is happening, and how I can fix it?
CDCDCDCDmeans uninitialized heap memory. https://stackoverflow.com/a/127404/487892Expoints to an array. Whencopy_adressis called, the parameterExends up incremented before it is evaluated in the expressionEx->adress, causing the address to be stored in the field of the second array element. Upon returning tomain, the globalExstill points to the first array element (it was not incremented), so the value ofEx->adressis uninitialized (the compiler set it to the distinctive0xCDCDCDCDpattern). However, since the behavior is undefined, this is just conjecture.