C語言函數指針
C語言編程語言允許將指針傳遞給函數。要做到這一點,隻需聲明函數參數作為指針類型。
下麵我們通過一個unsigned long指針的函數,並更改其反射回來在調用函數的函數裡麵的值一個簡單的例子:
#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 ", sec ); return 0; } void getSeconds(unsigned long *par) { /* get the current number of seconds */ *par = time( NULL ); return; }
當上述代碼被編譯和執行時,它產生了以下結果:
Number of seconds :1294450468
函數它可以接受的指針,還可以接受數組,如下麵的例子所示:
#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 yiibaier to the array as an argument */ avg = getAverage( balance, 5 ) ; /* output the returned value */ printf("Average value is: %f ", 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; }
當上述代碼被編譯在一起並執行時,它產生了以下結果:
Average value is: 214.40000