Memory allocation order in C ++

I wrote the following code trying to solve a problem that requests a structure similar to an array without using them:

#include <iostream>

int main(){
    int x = 132,y = 33,z = 87;

    int *i = &x;

    std::cout << x << " " << y << " " << z << "\n";
    std::cout << &x << " " << &y << " " << &z << "\n";
    std::cout << i << " " << i-1 << " " << i-2 << "\n";
    std::cout << *i << " " << *(i-1) << " " << *(i-2) << "\n";   
}

I found that the difference between the addresses of the two variables (& y- & x) is -1, and I subsequently adapted the code. I don’t understand why the last defined variable is highlighted “earlier” (which means the previous address).

I would honestly think & y- & x = 1.

Can you give me some pointers? (no pun intended: P) Oh, I know that code is bad practice - but does it have flaws or exceptions?

Thank you in advance

+3
source share
3 answers

This practice is as bad as it can be.

; ( , ), (.. ) .

, - undefined (, , ).

, , , , abs (& y - & x) 1 ( vars 16b).

+7

. Intel x86 .

+3

The compiler can place variables wherever they like. On many modern operating systems, the stack grows down, so if the compiler naively allocates the variables in stack order, the variable declared later is located at the bottom of the memory. But then again, this is completely arbitrary.

+1
source

Source: https://habr.com/ru/post/1787660/


All Articles