C pointer is passed to the function
C language allows you to pass a pointer to a function, you need to simply declare a function parameter is a pointer to type.
The following examples, we pass an unsigned long pointer to a function, and change the value in function:
#include <stdio.h> #include <time.h> void getSeconds(unsigned long *par); int main () { unsigned long sec; getSeconds( &sec ); /* 输出实际值 */ printf("Number of seconds: %ld\n", sec ); return 0; } void getSeconds(unsigned long *par) { /* 获取当前的秒数 */ *par = time( NULL ); return; }
When the above code is compiled and executed, it produces the following results:
Number of seconds :1294450468
Accept pointer as an argument of a function, but also accepts an array as a parameter, as follows:
#include <stdio.h> /* 函数声明 */ double getAverage(int *arr, int size); int main () { /* 带有 5 个元素的整型数组 */ int balance[5] = {1000, 2, 3, 17, 50}; double avg; /* 传递一个指向数组的指针作为参数 */ avg = getAverage( balance, 5 ) ; /* 输出返回值 */ 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; }
When the above code is compiled and executed, it produces the following results:
Average value is: 214.40000