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