这里介绍了函数指针的两种定义和调用方式。
例子中 f
和 f1
声明函数指针的方式是等价的,都是指向函数fun
,因为通过&fun
和fun
获取到的都是函数的地址(0x400586),同样的 f
,*f
,f1
,*f1
都是执行函数fun
的地址(0x400586),所以调用方式选取一个即可: f(3)
, (*f)(3)
, f1(3)
, (*f1)(3)
;
也可以使用typedef
定义函数指针,如FUNC
,这样在申明函数指针变量时写法比上述方法更简洁,同样func
和func1
两种声明方式也是等价的,func
,*func
, func1
, *func1
都是执行函数fun的地址(0x400586),所以调用方式选取一个即可: func(4)
, (*func)(4)
, func1(4)
,(*func1)(4)
.
一般地,使用typedef
定义函数指针,调用函数也是选取最简洁的方式: func(4)
.
#include <stdio.h>
void fun(int a)
{
printf("a=%d\n", a);
}
/*
用typedef定义一个函数指针,指向一个入参是一个int变量并且无返回值的函数
*/
typedef void (*FUNC)(int);
int main()
{
void (*f)(int) = &fun;
void (*f1)(int) = fun;
printf("Value of &f is %p\n", &f);
printf("Value of f is %p\n", f);
printf("Value of *f is %p\n", *f);
printf("Value of &fun is %p\n", &fun);
printf("Value of fun is %p\n", fun);
printf("Value of f1 is %p\n", f1);
printf("Value of *f1 is %p\n", *f1);
(*f)(3);
f(30);
f1(300);
(*f1)(3000);
FUNC func = fun;//推荐
FUNC func1 = &fun;
printf("\n");
printf("Value of &func is %p\n", &func);
printf("Value of func is %p\n", func);
printf("Value of *func is %p\n", *func);
printf("Value of &func1 is %p\n", &func1);
printf("Value of func1 is %p\n", func1);
printf("Value of *func1 is %p\n", *func1);
func(4);//推荐
(*func)(40);
func1(400);
(*func1)(4000);
return 0;
}
结果是:
Value of &f is 0x7ffced44dba0
Value of f is 0x400586
Value of *f is 0x400586
Value of &fun is 0x400586
Value of fun is 0x400586
Value of f1 is 0x400586
Value of *f1 is 0x400586
a=3
a=30
a=300
a=3000
Value of &func is 0x7ffced44dba8
Value of func is 0x400586
Value of *func is 0x400586
Value of &func1 is 0x7ffced44dbb0
Value of func1 is 0x400586
Value of *func1 is 0x400586
a=4
a=40
a=400
a=4000