指针算术运算
指针加法需要调整(加1:加一个单元格),
加一
int*p 4字节
char*p 1字节
short*p 2字节
double*p 8字节
调整的权重为指针去掉一个星号,然后求sizeof,如
int *p;p+1 加4字节= sizeof(int)
double *p;p+1 加8字节 = sizeof(double)
char **p;p+1 加4字节 = sizeof(char*)
指针加一个数字和减去一个数字都需要调整,调整的权重同上
指针+指针非法
指针-指针 表示间隔的单元个数。1、算出间隔的字节数(正负),2、除以调整的权重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
printf("%d\n",q-p); //8
printf("%d\n",(char **)q-(char **)p); //8
printf("%d\n",(short *)q-(short *)p); //16
printf("%d\n",(double *)q-(double *)p); //4
printf("%d\n",(char *)q-(char *)p) ; //32
printf("%d\n",(long long)q-(long long)p); //32
return 0;
}
int main()
{
int *p = (int *)0x2010;
printf("%x\n",p-2); //2008
printf("%x\n",(char***)p-2); //2008
printf("%x\n",(float*)p-2); //2008
printf("%x\n",(double **)p-2); //2008
printf("%x\n",(long long *)p-2); //2000
printf("%x\n",(char*)p-2); //200e
printf("%x\n",(unsigned long)p-2); //200e
return 0;
}
int main()
{
int *p = (int *)100;
printf("%d\n",p+4); //116
printf("%d\n",(char *)p+4); //104
printf("%d\n",(short *)p+4); //108
printf("%d\n",(unsigned long *)p+4); //116
printf("%d\n",(long long)p+4); //104
printf("%d\n",(char **)p+4); //116
printf("%d\n",(int ****)p+4); //116