wrong memory addressing?

Just for fun, I have written the following code:

1
2
3
4
5
6
7
8
int i1 = 10;
int i2 = 20;

// ptrints the space between i1 and i2
cout << &i1 - &i2 << endl;

// &i1 plus the difference
cout << *(&i1 + (&i1 - &i2)) << endl;


I know that a int has a size of 4 bytes and so in memory, the difference must be 4 bytes, right? The first cout prints 3. Anyway, then the second cout must be print the memory location of i1 plus the difference, so it must be work right, but it doesn't and on the console I get unexpected random numbers. Why my "approach" won't work?
i1 has the highest memory address so try change to cout << *(&i2 + (&i1 - &i2)) << endl; It will probably print the value of i1.

I don't think any of this is guaranteed by C++ standard.
Last edited on
closed account (zb0S216C)
There's no guarantee that each variable is situated right after the previous one. Allow me to elaborate. Variable A occupies addresses 0x0 -to- 0x3 (4 address), and variable B occupies addresses 0x10 -to- 0x13. The difference is 8 (I think) addresses. Each variable can be located at different places within memory; never in the same place, never next to each other (it's possible, but highly unlikely).

Arrays are different. Each element of an array is aligned with each other without padding between each element.

Wazzak
Thanks!
Topic archived. No new replies allowed.