I have been studying pointer of c plus plus.
I created function called pp which takes reference as parameter. then print its memory address, value and size.
And I create variable a, b assigned it to 10, 25 indivisually.
And variable pa, pb which points to variable a, b.
My environment is MacOS M1 Architecture and I compiled it using c++17 version.
#include <iostream>
void pp(int & i)
{
std::cout << &i << " " << i << " " << sizeof(i) << "\n";
}
int main(int argc, char * argv[])
{
int a = 10;
int b = 25;
int* pa = &a;
int* pb = &b;
pp(a);
pp(b);
return 0;
}
when I compile below my c++ code, output is like this.
0x16b802e7c 10 4
0x16b802e78 25 4
My question is about relation of memory address between variable a and b.
I have already know there is gap of 4 size in addresss because of size for integer is 4 bytes.
It's okay, but It confuse me that variable address of a is higher than address of b although variable a was created before initializing variable b.
when this code is compiled then executed in other platform, output is different.
address of variable a is lower than b.
So in my environment which is macOS, If I write code like below.
*(pb - 1) = 17;
It doesn't change value of a. because memory address b is lower than a although My expectinon is to change value of a.
If I want to change value of a accesing memory address, I have to add one to pointer of b like below.
*(pb + 1) = 17;
as a result, I want to know why this difference of memory allocation by platform is to be and what theory I have to know to understand how it works.
Might it be relations about endian?