#include<stdio.h>
int main()
{
int arr[10]={1,2,3,4,5,6};
int *p = arr;
p++;
printf("%d %d\n",arr[0],arr[1]);
return 0;
}
(2) 指针加数字:指针加法需要调整,调整的权重为指针去掉一个*号,求sizeof。
例:#include<stdio.h>
int main()
{
int *p = (int*)1000;
printf("%d\n",(char ***)p+2);//1008
printf("%d\n",(short *)p+2);//1004
printf("%d\n",(double **)p+2);//1008
printf("%d\n",(unsigned long *)p+2);//1008
printf("%d\n",(char *)p+2);//1002
printf("%d\n",(unsigned long long )p+2);//1002//这里的unsigned long long是指强转指针的类型
return 0;
}
(4)指针-数字:需要调整,调整的权重位sizeof指针去掉一个*
注:和指针+数字算法相同
#include<stdio.h>
int main()
{
int *p = (int *)0x2010;//注意是十六进制
printf("%x\n",p-2);//2008
printf("%x\n",(float *)p-2);//2008
printf("%x\n",(double *)p-2);//2000
printf("%x\n",(short *)p-2);//200c
printf("%x\n",(unsigned long *)p-2);//2008
printf("%x\n",(long *)p-2);//2008
printf("%x\n",(long long)p-2);//200e
printf("%x\n",(char *)p-2);//200e
return 0;
}
(5)指针-指针:间隔的单元个数,需要调整,调整的权重位sizeof(指针去掉一个*)
注:指针-指针的计算:1、计算间隔的字节数,2、除以权重
#include<stdio.h>
int main()
{
int arr[10] = {0};
int *p = &arr[1];//x+4
int *q = &arr[7];//x+28
printf("%d\n",p-q);//-6
printf("%d\n",q-p);//6
printf("%d\n",(short *)q-(short *)p);//12
printf("%d\n",(long long*)q-(long long *)p);//3
printf("%d\n",(double *)q-(double *)p);//3
printf("%d\n",(unsigned long)q-(unsigned long)p);//24
printf("%d\n",(char **)q-(char **)p);//6
return 0;
}