【C语言】指针的算术运算

匿名 (未验证) 提交于 2019-12-03 00:30:01

之前在学习指针时,我们知道指针其实也是一种变量,既然这样,那么指针应该和普通变量一样,可以进行算术运算。下面我们介绍指针的加减运算。
先看一个实例:
#include <stdio.h>      int main()   {       int arr[10] = {1,2,3,4};       int *p = arr;       *p = 10;     printf("%d\n",*p);       p++;     *p = 20;       printf("%d\n",*p);       return 0;   }  

假设其首地址为1000,则整个数组对应的地址如下:
图1 数组arr对应地址

图2 修改数组arr首元素的内容

图3 指针p向后移一个数组
十进制的2转化为十六进制为0x00000002。因电脑使用的小端,即低地址存放小数据,如下图所示:
图4 前两个数组元素

图5 指针p加一个字节
arr[1]修改为20,如图:

指针p加一个单元格
#include <stdio.h>      int main()   {       int *p = (int *)1000;       printf("%d\n",p+5);//1020       printf("%d\n",(short *) p+5);//1010       printf("%d\n",(unsigned long *)p+5);//1020       printf("%d\n",(double *)p+5);//1040       printf("%d\n",(char ***)p+5);//1020       printf("%d\n",(char *)p+5);//1005       printf("%d\n",(long long)p+5);//1005          return 0;   }  

图7 指针加法实例运行结果
#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);//2008      printf("%x\n",(long long *)p-2);//2000     printf("%x\n",(short *)p-2);//200c      printf("%x\n",(char *)p-2);//200e       printf("%x\n",(unsigned long)p-2);//200e        return 0;   }  
图8 指针减法实例运行结果

#include <stdio.h>  int main()   {       int arr[10] = {0};//x       int *p = &arr[9];//x+36       int *q = &arr[1];//x+4       printf("%d\n",p-q);//8       printf("%d\n",q-p);//-8       printf("%d\n",(short *)p-(short *)q);//16       printf("%d\n",(long *)p-(long *)q);//8       printf("%d\n",(char **)p-(char **)q);//8       printf("%d\n",(double *)p-(double *)q);//4       printf("%d\n",(long long)p-(long long)q);//32       printf("%d\n",(char *)p-(char *)q); //32          return 0;   }    




易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!