next up previous contents
Next: 從函式回傳陣列指標 Up: 指標 Previous: 傳送指標到函式   Contents   DYWANG_HOME

傳送陣列位址到函式

  1. 範例二:傳送陣列位址至函式,函式運算會改變陣列內容。
    [dywang@dyw219 zzz]$ vim pointer9.c
    [dywang@dyw219 zzz]$ cat pointer9.c
    #include <stdio.h>
     
    float getAverage(int *arr, int size)
    {
    	int i, sum=0;       
    	float avg;          
     
    	for ( i=0; i<size; ++i) {
    		sum += arr[i];
    	}
    	avg = (float)sum/size;
    	return avg;
    }
    
    main () {
    	int balance[] = {1000, 2, 3, 17, 50};
    	float avg;
     
    	avg = getAverage( balance, 5 ) ;
    	printf("Average(1000, 2, 3, 17, 50) = %f\n", avg );
    }
    
  2. 編譯
    [dywang@dyw219 zzz]$ gcc -o pointer9 pointer9.c
    
  3. 執行結果
    [dywang@dyw219 zzz]$ ./pointer9
    Average(1000, 2, 3, 17, 50) = 214.399994
    



De-Yu Wang 2021-01-11