关于C语言指针的实验验证
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 void main() 5 { 6 struct ll{ 7 unsigned int d; 8 unsigned short ch; 9 }c; 10 c.d=6; 11 c.ch=0xfffe; 12 13 14 struct ll *p,*p1,*p2; 15 16 17 p=&c; 18 printf("c.ch=%lx\n\np=%lx\n\n",c.ch,p); 19 20 21 p1=p+4; 22 23 printf("p1=%lx\n",*p1); 24 25 26 27 //方式一: 28 p2=(long)p+4; 29 30 printf("*p2=%lx\n\n",*p2); 31 32 //方式二 : 33 unsigned short * x; 34 x=(long)p+4; 35 printf("x=%lx\n",*x); 36 37 return 0; 38 }
struct ll 大小为8字节(4+2+2=8,为了对齐填充了2字节)。
由以上的代码运行发现,将指针运算P=P+4,得出的地址 = P地址的值 +(4*8).
即 gcc 将代码 P=P+4 优化为指向当前地址后的第 4 个struct ll;
所以,得到的数值为无意义的值;
而方式一将指针的转变为 long 类型的数据再进行运算得出的值为正确的指针值。
但由于指针p指向的类型为struct ll,此结构大小为8字节(4+2+2=8,为了对齐填充了2字节)。
所以得到的数据为8字节的,低二字节有效,高六字节无效。
方式二将结构的地址的值转变为 long类型的数值 并加 4 (第一个参数为 int )传给类型为 short* 的指针x ,
得到对应地址的数值。从此地址开始读取 2 字节(short)位数据 ,得出的数值正确。