if I have the following code:
int i = 5;
void * ptr = &i;
printf("%p", ptr);
Will I get the LSB address of i, or the MSB?
Will it act differently between platforms?
Is there a difference here between C and C++?
Consider the size of int
is 4 bytes. Always &i
will gives you the first address of those 4 bytes.
If the architecture is little endian, then the lower address will have the LSB like below.
+------+------+------+------+ Address | 1000 | 1001 | 1002 | 1003 | +------+------+------+------+ Value | 5 | 0 | 0 | 0 | +------+------+------+------+
If the architecture is big endian, then the lower address will have the MSB like below.
+------+------+------+------+ Address | 1000 | 1001 | 1002 | 1003 | +------+------+------+------+ Value | 0 | 0 | 0 | 5 | +------+------+------+------+
So &i
will give LSB address of i
if little endian or it will give MSB address of i
if big endian
In mixed endian mode also, either little or big endian will be chosen for each task dynamically.
Below logic will tells you the endianess
int i = 5;
void * ptr = &i;
char * ch = (char *) ptr;
printf("%p", ptr);
if (5 == (*ch))
printf("\nlittle endian\n");
else
printf("\nbig endian\n");
This behaviour will be same for both c
and c++