20、【C语言基础】函数指针与回调函数

函数指针

函数指针是指向函数的指针变量。

通常我们说的指针变量是指向一个整型、字符型或数组等变量,而函数指针是指向函数。

函数指针可以像一般函数一样,用于调用函数、传递参数。

函数指针变量的声明:

typedef int (*fun_ptr)(int,int); // 声明一个指向同样参数、返回值的函数指针类型

【示例】

 1 #include <stdio.h>
 2  
 3 int max(int x, int y)
 4 {
 5     return x > y ? x : y;
 6 }
 7  
 8 int main(void)
 9 {
10     /* p 是函数指针 */
11     int (* p)(int, int) = & max; // &可以省略
12     int a, b, c, d;
13  
14     printf("请输入三个数字:");
15     scanf("%d %d %d", & a, & b, & c);
16  
17     /* 与直接调用函数等价,d = max(max(a, b), c) */
18     d = p(p(a, b), c); 
19  
20     printf("最大的数字是: %d
", d);
21  
22     return 0;
23 }

执行结果:

请输入三个数字:1 2 3
最大的数字是: 3

回调函数

函数指针作为某个函数的参数

函数指针变量可以作为某个函数的参数来使用的,回调函数就是一个通过函数指针调用的函数。

简单讲:回调函数是由别人的函数执行时调用你实现的函数。

【示例】

 1 #include <stdlib.h>  
 2 #include <stdio.h>
 3  
 4 // 回调函数
 5 void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
 6 {
 7     for (size_t i=0; i<arraySize; i++)
 8         array[i] = getNextValue();
 9 }
10  
11 // 获取随机值
12 int getNextRandomValue(void)
13 {
14     return rand();
15 }
16  
17 int main(void)
18 {
19     int myarray[10];
20     populate_array(myarray, 10, getNextRandomValue);
21     for(int i = 0; i < 10; i++) {
22         printf("%d ", myarray[i]);
23     }
24     printf("
");
25     return 0;
26 }

执行结果:

16807 282475249 1622650073 984943658 1144108930 470211272 101027544 1457850878 1458777923 2007237709 
原文地址:https://www.cnblogs.com/Long-w/p/9675321.html