1、指针加减数字是合法的
指针加减数字表示的意义是指针在数组中位置的移动
指针加减法规则
指针加减法需要调整,调整的权重是指针本身去掉一个*,再求sizeof()
eg:
int main()
{
//指针减数字
int *p = (int *)0x1010;//定义一个整型指针变量p赋值为16进制数0x1010
printf("%x\n",p-1);//100c 去掉一个*,属于int型,sizeof()是4,1010-4 = 100c(注意是16进制数)
printf("%x\n",p-2);//1008
printf("%x\n",(short *)p-2);//100c
printf("%x\n",(char *)p-2);//100e 强转成char类型的指针变量,去掉一个*后属于char型,sizeof()是1,1010-2
printf("%x\n",(double *)p-2);//1000
printf("%x\n",(float *)p-2);//1008
printf("%x\n",(long long)p-2);//100e 不是指针变量,所以不用求sizeof(),直接-2
printf("%x\n",(double **)p-2);//1008
printf("%x\n",(char **)p-2);//1008 去掉一个*,还属于指针变量,sizeof()是4
//指针加数字
int *p = (int *)10000;
printf("%d\n",p+1);//10004
printf("%d\n",p+4);//10016
printf("%d\n",(char *)p+4);//10004
printf("%d\n",(short *)p+4);//10008
printf("%d\n",(double *)p+4);//10032
printf("%d\n",(unsigned long long )p+1);//10001
printf("%d\n",(int ***)p+1);//10004
printf("%d\n",(double **)p+1);//10004
printf("%d\n",(float **)p+10);//10040
return 0;
}
2、指针减指针合法
指针减指针的意义是两个地址之间相隔的单元格数
指针 - 指针规则
①算出两个指针间隔的字节数
②除以调整的权重,调整的权重是指针本身去掉一个*,再求sizeof()
eg:
int main()
{
int arr[10] = {0};//x
int *p = &arr[1];//x+4
int *q = &arr[9];//x+36
printf("%d\n",p-q);//-8 间隔的字节数为(1 - 9)*4= - 32,sizeof()是4,-32/4=-8
printf("%d\n",q-p);//8
printf("%d\n",(short *)q-(short *)p);//16 32/2=16
printf("%d\n",(char **)q-(char **)p);//8 32/4=8
printf("%d\n",(double *)q-(double *)p);//4
printf("%d\n",(long *)q-(long *)p);//8
printf("%d\n",(char *)q-(char*)p);//32
printf("%d\n",(long long)q-(long long)p);//32 非指针不需调整
//printf("%d\n",(int *)q-(short *)p);//error
return 0;
}
注意:不同类型的指针不允许相减