1. 指针+数字
指针加法需要调整,调整的权重为sizeof(指针去掉一个*)
P1+3
P1+1(3和1为权重)
Int*p1 p1++ 加sizeof(int)
shaort*p2 p2++ 加sizeof(short)
double*p3 p3++ 加sizeof(double)
int *p = (int *)2000; 整型占四个字节
printf("%d\n",p+2); 2008 =2000+4*2
printf("%d\n",(short *)p+2); 2004 short占两个字节
printf("%d\n",(float *)p+2); 2008 float 占四个字节
printf("%d\n",(double *)p+2); 2016 doble 占八个字节
printf("%d\n",(double **)p+2); 2008 去掉星号仍然为指针,指针占四个字节
printf("%d\n",(char *)p+2); 2002 字符型占一个字节
printf("%d\n",(unsignedlong)p+2); 2002直接加数字
2. 指针-数字
指针加法需要调整,调整的权重为sizeof(指针去掉一个*)
十进制
int *p = (int *)2010;
printf("%d\n",p-2);//2008
printf("%d\n",(short *)p-2);//2006
printf("%d\n",(float *)p-2);//2002
printf("%d\n",(double **)p-2);//1994
printf("%d\n",(char *)p-2);//2008
printf("%d\n",(unsigned long)p-2);//2008
十六进制
int *p = (int *)0x2010;
printf("%x\n",p-2);//2008
printf("%x\n",(short *)p-2);//200c(借一位为16,16-4=12,16进制12表示为C,下同)
printf("%x\n",(double *)p-2);//2000
printf("%x\n",(long long ***)p-2);//2008(去掉星号为二级指针,二级指针仍为指针)
printf("%x\n",(float *)p-2);//2008
printf("%x\n",(char *)p-2);//200e
printf("%x\n",(unsigned long long)p-2);//200e
3. 指针+指针非法
4. 指针-指针合法,表示间隔的单元格数
指针-指针需要调整,调整的权重为sizeof(指针去掉一个*)
分两步:(1)算出间隔字节数
(2)除以调整的权重
int arr[10] = {0};
int *p = &arr[1]; // 4
int *q = &arr[9]; // 36
printf("%d\n",p-q); //-8
printf("%d\n",q-p); //8
printf("%d\n",(short*)q-(short *)p); //16(36-4)/2
printf("%d\n",(long*)q-(long *)p); //8 (36-4)/4
printf("%d\n",(float*)q-(float *)p); //8 (36-4)/4
printf("%d\n",(longlong **)q-(long long **)p); //8 (36-4)/4(去掉星号仍为指针)
printf("%d\n",(double*)q-(double *)p);//4(36-4)/8
printf("%d\n",(char*)q-(char *)p);//32(36-4)/1
printf("%d\n",(long)q-(long)p);//32 (36-4)