The Code used
#include<stdio.h>
struct st
{
char a;
short c;
int b;
};
struct st s1;
int main()
{
printf("%p %p \n",(&s1.b)-1, &s1);
}
If I print the address of &s1.b it prints 0x804a01c and &s1.b-2 prints 0x804a018
why it is printing same address 0x804a01c if i select &s1.b-1 ?
Thank you for posting your code. Now I see the issue. It is because of padding. To wit:
On my machine this prints
You might think, shouldn’t
sizeof(struct st)be1 + 2 + 4 = 7? That’s certainly a reasonable thought but because of alignment issues there is padding betweenaandc. Therefore, in memory, the struct looks like the following (relative to the first byte of the struct):Consequently (relative to
&s1):This is why both
&s1and&s1.b - 1will print the same address. In particular ifthen
and
and
Note, finally, that this is implementation-specific behavior. This is not portable!