1. 程式人生 > >指標加減指標與數字( + and - )

指標加減指標與數字( + and - )

今天要記錄一個很重要的知識點那就是指標加減一個數和指標加減指標。

1、指標 + 一個數     

2、指標 - 一個數     

3、指標 + 指標      ×

4、指標 指標       

由上圖可知,指標加指標是不可行的。

1、指標加減數

那指標加減一個數表示什麼意思呢,若加的數字為n,則它的意思為加n個單元格,但是他需要調整,調整的權重為sizeof(指標去掉一個*

練習如下:

1)加法:

int *p = (int*)2000;                              答案

     printf("%d\n",p+4);            

             //2016

     printf("%d\n",(short *)p+4);                  //2008

     printf("%d\n",(double *)p+4);               

//2032

     printf("%d\n",(float **)p+4);                 //2016

     printf("%d\n",(unsigned short*)p+4);        //2008

     printf("%d\n",(long *)p+4);                  //2016

     printf("%d\n",(char *)p+4);                  //2004

     printf("%d\n",(unsigned longlong)p+4);   //2004(並非指標)

2)減法:

int *p = (int*)0x2010;                           答案

     printf("%x\n",p-2);                         //2008

     printf("%x\n",(short *)p-2);                 //200c

     printf("%x\n",(unsigned long*)p-2);       //2008

     printf("%x\n",(long long **)p-2);          //2008

     printf("%x\n",(float *)p-2);                //2008

     printf("%x\n",(double *)p-2);              //2000

     printf("%x\n",(char *)p-2);                //200e

     printf("%x\n",(unsigned long)p-2);       //200e

2、指標-指標

指標-指標表示的是他們兩個指標之間的格子數。我們首先要算出兩個指標之間的位元組數,再除以調整的權重。

練習如下:

intarr[10] = {1};                                  格子數

      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",(short *)q-(short*)p);             //16

      printf("%d\n",(double*)q-(double *)p);          //4

      printf("%d\n",(int ***)q-(int***)p);               //8

      printf("%d\n",(char **)q-(char**)p);              //8

      printf("%d\n",(long)q-(long)p);                  //32

綜上所述,指標的所有算術運算都需要調整,調整的權重為sizeof(指標去掉一個*)