What you're doing is Undefined Behaviour and you should not try and use such details in any serious program but try this:
#include <iostream>
int main(){
int a = 42;
int b = 1;
int c = 2;
int d = 2;
int e = 2;
int *p = &c;
int *q=p+1;
std::cout << "sizeof(int) = " << sizeof(int) << '\n';
std::cout << "&a = " << &a << '\n';
std::cout << "&b = " << &b << '\n';
std::cout << "&c = " << &c << '\n';
std::cout << "&d = " << &d << '\n';
std::cout << "&e = " << &e << '\n';
std::cout << "q = " << q << '\n';
}
Typical Output:
sizeof(int) = 4
&a = 0x7fff7c418d74
&b = 0x7fff7c418d78
&c = 0x7fff7c418d7c
&d = 0x7fff7c418d80
&e = 0x7fff7c418d84
q = 0x7fff7c418d80
You will probably see q = &d
(as here) or possibly q = &b
;
Then comment out the output line for the one that matches.
For me that's std::cout << "&d = " << &d << '\n';
Typical Output:
sizeof(int) = 4
&a = 0x7fff62baf498
&b = 0x7fff62baf49c
&c = 0x7fff62baf4a0
&e = 0x7fff62baf4a4
q = 0x7fff62baf4a4
The actual addresses will vary between execution but typically bear fixed relationships in terms of the size of an int (typically 4).
On my platform you'll see an int is 4 bytes and the pointers are output as hexadecimal addresses and all differ by 4. That is the most common case.
That is, in this example and likely on your platform you'll see the local variables occupy a consecutive block of memory given away by the pointer addresses.
What you're most likely seeing is that when you don't use x
in your code (d
in mine) the compiler optimises it out of existence.
Pointer arithmetic (e.g. p-1
) is only valid within an array.
However p+1
is always legal because variables always like singleton arrays and there's a special rule for being allowed to point to one past the end of an array.
What is undefined is to dereference p+1
even if it points to one of the other variables (which it likely will). It is not a 'safely derived pointer'.
p-1
will probably give you the result you expect! But the result of p-1
is Undefined.
This is illustrative to understand how the stack works. Never ever (ever!) do this as part of any serious coding effort.