这是有问题的代码
#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;
}
sizeof(struct test) 打印 6,所以我会expect to see:
6 0xffa 0x1006
相反我得到
6 0x1024 0xfdc
上次我检查时,0x24 或 36 不等于 6。它甚至与我所知的任何内容都不相符。我完全不知所措。
有人可以向我解释为什么我会得到这些值吗?
问题是当你进行指针算术时,它会增加一个multiple数据类型的大小。
所以你有效地做的就是加上sizeof(struct test)
.
Since sizeof(struct test) = 6
,您将地址增加6 * 6 = 36
。因此为什么你会得到0x1024
and 0xfdc
代替0x1006
and 0xffa
。 (您还切换了+
and -
,但这只是小事。)
相反,只需这样做:
printf("%x %p %p\n",
sizeof(struct test),
a + 1,
a - 1);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)