概念
- 函数指针:是指向函数的指针变量。通常我们说的指针变量是指向一个整型、字符型或数组等变量,而函数指针是指向函数。函数指针可以像一般函数一样,用于调用函数、传递参数。
- 指针函数:顾名思义就是带有指针的函数,即其本质是一个函数,只不过这种函数返回的是一个对应类型的地址。
声明
- 函数指针变量
typedef int (*fun_ptr)(int,int); // 声明一个指向同样参数、返回值的函数指针类型
- 指针函数
type *func (type , type)
如:int *max(int x, int y)
示例
- 函数指针
#include <stdio.h>
int max(int x, int y)
{
return x > y ? x : y;
}
int main(void)
{
/* p 是函数指针 */
int (* p)(int, int) = & max; // &可以省略
int a, b, c, d;
printf("请输入三个数字:");
scanf("%d %d %d", & a, & b, & c);
/* 与直接调用函数等价,d = max(max(a, b), c) */
d = p(p(a, b), c);
printf("最大的数字是: %d\n", d);
return 0;
}
[root@localhost test]# ./fun_pointer
请输入三个数字:1 2 3
最大的数字是: 3
- 指针函数
#include <iostream>
using namespace std;
int *GetNum(int x); //指针函数声明形式
void main(void)
{
cout<<"===============start================"<<endl;
int num;
cout<<"Please enter the number between 0 and 6: ";
cin>>num;
cout<<"result is:"<<*GetNum(num)<<endl; //输出返回地址块中的值
}
int *GetNum(int x) {
static int num[]={0,1,2,3,4,5,6};
return &num[x]; //返回一个地址
}
综上(区别)
函数指针是指向函数的指针变量,它会和回调函数(下一篇博客会讲回调函数)结合起来使用(实际上回调函数就是用的函数指针);而指针函数与正常的函数并没有什么本质的区别,只是它返回的是一个地址。