概念&例程
在C语言中,函数本身不是变量,但是可以定义指向函数的指针,也称作函数指针,函数指针指向函数的入口地址。这种类型的指针可以被赋值、存放在数组中、传递给函数以及作为函数的返回值等等
例程一:
#include "stdio.h"
#include "string.h"
int str_comp(const char *m,const char *n)
{
if(strcmp(m,n) == 0)
return 0;
else
return 1;
}
/* 函数 comp 接受一个函数指针作为它的第三个参数 */
void comp(char *a,char *b,int (*prr)(const char *,const char*))
{
if(prr(a,b) == 0)
printf("str1 = str2\n");
else
printf("str1 != str2\n");
} // 声明一个函数 comp ,注意该函数的第三个参数,是一个函数指针
int main()
{
char str1[20]; // 声明一个字符数组
char str2[20];
// int (*p)(const char *,const char *) = str_comp; // 声明并初始化一个函数指针,该指针所指向的函数有两个 const char 类型的指针,且返回值为 int 类型
scanf("%s %s", &str1, &str2);
comp(str1,str2,str_comp); // 函数指针 p 作为参数传给 comp 函数
return 0;
}
例程二:
#include <stdlib.h>
#include <stdio.h>
// 回调函数
void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
for (size_t i=0; i<arraySize; i++)
array[i] = getNextValue();
}
// 获取随机值
int getNextRandomValue(void)
{
return rand();
}
int main(void)
{
int myarray[10];
/* getNextRandomValue 不能加括号,否则无法编译,因为加上括号之后相当于传入此参数时传入了 int , 而不是函数指针*/
populate_array(myarray, 10, getNextRandomValue);
for(int i = 0; i < 10; i++) {
printf("%d ", myarray[i]);
}
printf("\n");
return 0;
}