next up previous contents
Next: 指標陣列 Up: 指標(pointers) Previous: 指標   Contents

指標算術

  1. 指標是記憶體位址,是一個數字,所以可以做 ++, --, +, - 等運算。
    ptr++
    
  2. 指標遞增
    #include <stdio.h>
    
    const int MAX = 3;
    
    int main ()
    {
       int  var[] = {10, 100, 200};
       int  i, *ptr;
    
       /* let us have array address in pointer */
       ptr = var;
       for ( i = 0; i < MAX; i++)
       {
    
          printf("Address of var[%d] = %x\n", i, ptr );
          printf("Value of var[%d] = %d\n", i, *ptr );
    
          /* move to the next location */
          ptr++;
       }
       return 0;
    }
    
  3. 指標遞減
    #include <stdio.h>
    
    const int MAX = 3;
    
    int main ()
    {
       int  var[] = {10, 100, 200};
       int  i, *ptr;
    
       /* let us have array address in pointer */
       ptr = &var[MAX-1];
       for ( i = MAX; i > 0; i--)
       {
    
          printf("Address of var[%d] = %x\n", i, ptr );
          printf("Value of var[%d] = %d\n", i, *ptr );
    
          /* move to the previous location */
          ptr--;
       }
       return 0;
    }
    
  4. 指標比較
    #include <stdio.h>
    
    const int MAX = 3;
    
    int main ()
    {
       int  var[] = {10, 100, 200};
       int  i, *ptr;
    
       /* let us have address of the first element in pointer */
       ptr = var;
       i = 0;
       while ( ptr <= &var[MAX - 1] )
       {
    
          printf("Address of var[%d] = %x\n", i, ptr );
          printf("Value of var[%d] = %d\n", i, *ptr );
    
          /* point to the previous location */
          ptr++;
          i++;
       }
       return 0;
    }
    



2015-01-16