在学习C语言的时候老是搞不清什么试函数指针,什么试指针函数。主要怪自己语文没学好,其实是很好区分的。两个的重点后两个字,前两个都是修饰词。
所谓的函数指针可以理解成指针,存放的是地址。函数地址是一个函数的入口地址,函数名代表了函数的入口地址。到某个函数需要调用的时候,将函数指针的地址作为一个参数传给那个函数。
函数指针的一般形式:
数据类型 (*变量名称)(定义的参数及类型)
下面举一个简单的例子:
#include <stdio.h>
int pluc(int a, int b);
int minus(int a, int b);
int test(int a, int b, int (*pFunc) (int, int));
int main(int argc, char **argv)
{
int x = 5, y = 8;
int (*pFunc) (int, int); // 定义一个函数指针
pFunc = pluc;
printf("%d\n", (*pFunc) (x,y)); //等价于调用pluc(x,y)
pFunc = minus;
printf("%d\n", (*pFunc) (x,y));
printf("%d\n",test(15, 5, pluc));
printf("%d\n", test(15, 5,minus));
return 0;
}
int pluc(int a, int b)
{
return (a + b);
}
int minus(int a, int b)
{
return (a - b);
}
int test(int a, int b, int (*pFunc) (int ,int))
{
return (*pFunc) (a, b);
}
运行结果如下: