Here is the code in question
#include <stdio.h>
struct test {
unsigned char t;
unsigned short u;
unsigned char v;
};
int main ()
{
struct test * a = (void *) 0x1000;
printf("%x %p %p\n",
sizeof(struct test),
a + sizeof(struct test),
a - sizeof(struct test));
return 0;
}
The sizeof(struct test) prints 6, so I would expect to see:
6 0xffa 0x1006
Instead I get
6 0x1024 0xfdc
Last time I checked, 0x24, or 36, was not equal to 6. It’s not even aligned to anything that I can tell. I am at a complete loss.
Can someone please explain to me why I’m getting these values?
The problem is that when you do pointer arithmetic, it increments by a multiple of the size of the datatype.
So what you’re effectively doing is adding by the square of
sizeof(struct test).Since
sizeof(struct test) = 6, you are incrementing the address by6 * 6 = 36. Hence why you get0x1024and0xfdcinstead of0x1006and0xffa. (You also switched the+and-, but that’s a small thing.)Instead, just do this: