目录

将指针传递给C中的函数(Passing pointers to functions in C)

C编程允许将指针传递给函数。 为此,只需将函数参数声明为指针类型即可。

下面是一个简单的例子,我们将一个无符号长指针传递给一个函数,并改变函数内部的值,该值反映在调用函数中 -

#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;
}

编译并执行上述代码时,会产生以下结果 -

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 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;
}

当上面的代码一起编译并执行时,它会产生以下结果 -

Average value is: 214.40000
↑回到顶部↑
WIKI教程 @2018