next up previous contents
Next: 從函式回傳指標 Up: 指標(pointers) Previous: 指標指向指標   Contents

傳送指標到函式

  1. 範例一:傳送 unsigned long 變數 sec 的位址到函式 getSeconds,並改變 sec 內容。
    #include <stdio.h>
    #include <time.h>
     
    void getSeconds(unsigned long *par);
    
    int main ()
    {
       unsigned long sec;
    
    
       getSeconds( &sec );
    
       /* print the actual value */
       printf("Number of seconds: %ld\n", sec );
    
       return 0;
    }
    
    void getSeconds(unsigned long *par)
    {
       /* get the current number of seconds */
       *par = time( NULL );
       return;
    }
    
  2. 範例二:傳送陣列位址至函式,函式運算會改變陣列內容。
    #include <stdio.h>
     
    /* function declaration */
    double getAverage(int *arr, int size);
     
    int main ()
    {
       /* an int array with 5 elements */
       int balance[5] = {1000, 2, 3, 17, 50};
       double avg;
     
       /* pass pointer to the array as an argument */
       avg = getAverage( balance, 5 ) ;
     
       /* output the returned value  */
       printf("Average value is: %f\n", avg );
        
       return 0;
    }
    
    double getAverage(int *arr, int size)
    {
      int    i, sum = 0;       
      double avg;          
     
      for (i = 0; i < size; ++i)
      {
        sum += arr[i];
      }
     
      avg = (double)sum / size;
     
      return avg;
    }
    



2015-01-16