版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cmh477660693/article/details/75514096
#include <stdio.h>
struct BBB
{
long num;
char *name;
short int data;
char ha;
short ba[5];
}*p;
int main()
{
p = 0x1000000;
printf(" p+0x200=0x%08x\n", p+0x200);
printf(" (Ulong)p+0x200=0x%08x\n", (unsigned long)p+0x200);
printf("(char*)p+0x200=0x%08x\n", (char*)p+0x200);
printf("(short*)p+0x200=0x%08x\n", (unsigned short*)p+0x200);
printf("(int*)p+0x200=0x%08x\n", (unsigned int*)p+0x200);
return 0;
}
运行结果:
p+0x200=0x01003000
(Ulong)p+0x200=0x01000200
(char*)p+0x200=0x01000200
(short*)p+0x200=0x01000400
(int*)p+0x200=0x01000800
解答:
假设在32位CPU上,
sizeof(long) = 4 bytes
sizeof(char *) = 4 bytes
sizeof(short int) = sizeof(short) = 2 bytes
sizeof(char) = 1 bytes
由于是4字节对齐,
sizeof(struct BBB) = sizeof(*p)
= 4 + 4 + 2 + 1 + 1/补齐/ + 2*5 + 2/补齐/ = 24 bytes (经Dev-C++验证)
p=0x1000000;
p+0x200=__;
=0x1000000 + 0x200*24
(char*)p+0x200 = 0x1000000 + 0x200 * 1 = 0x01000200
(short*)p+0x200 = 0x1000000 + 0x200 * 2 = 0x01000400
(int*)p+0x200 = 0x1000000 + 0x200 * 4 = 0x01000800
结论:
某一类型的指针 + 一个常数 = 这个常数 * 指针所指区域的大小。