指针函数:
指针函数,简单的来说,就是一个返回指针的函数,其本质是一个函数,而该函数的返回值是一个指针。
指针函数相对简单,不多做描述。
声明格式为:*类型标识符 函数名(参数表)
如:
int *fun(int x,int y);
函数指针,其本质是一个指针变量,该指针指向这个函数。总结来说,函数指针就是指向函数的指针。
声明格式:类型说明符 (*函数名) (参数)
如下:
int (*fun)(int x,int y);
1
函数指针是需要把一个函数的地址赋值给它,有两种写法:
fun = &Function;(函数本质为一个指针,再取地址,可以认为这是一种通用形式)
fun = Function;(直接将指针赋值)
取地址运算符&不是必需的,因为一个函数标识符就表示了它的地址,如果是函数调用,还必须包含一个圆括号括起来的参数表。
调用函数指针的方式也有两种:
x = (*fun)();
x = fun();
两种方式均可,其中第二种看上去和普通的函数调用没啥区别,如果可以的话,建议使用第一种,因为可以清楚的指明这是通过指针的方式来调用函数。当然,也要看个人习惯,如果理解其定义,随便怎么用都行啦。
关于函数指针用法,一般会和typedef连用,我认为有以下几个因素:
1、使用 typedef 定义函数指针,代码看起来更简洁,也更不容易出错。
2、当定义一个传参包含函数指针的函数时比较方便。
3、当函数指针作为其它函数的参数,特别是作为返回值时,直接使用的函数指针无法编译(与2类似)。
#include <stdio.h>
typedef int (*fun)(int,char *);
//int (*fun2)(int,char *);
int test_fun(int a, char *b)
{
printf("a is %d\n",a);
printf("b is %s\n",b);
return 1;
}
void test(int a,char * b,fun f)
{
printf("get in test---\n");
f(a,b);
printf("get out test---\n");
}
#if 0
void test2(int a,char * b,fun2 f)
{
printf("get in test---\n");
f(a,b);
printf("get out test---\n");
}
#endif
int main(int argc,char * argv[])
{
fun f = test_fun;
printf("printf f is %p\n",f);
test(1,"first type",f);
fun f1 = &test_fun;
printf("printf f1 is %p\n",f1);
test(2,"second type",f1);
}
执行结果:
printf f is 0x400566
get in test---
a is 1
b is first type
get out test---
printf f1 is 0x400566
get in test---
a is 2
b is second type
get out test---
从结果可以看出两种赋值方式是一致的,这种调用可以认为是函数指针相对通用的用法。