函数指针(a pointer to a function)

这里介绍了函数指针的两种定义和调用方式。

例子中 ff1声明函数指针的方式是等价的,都是指向函数fun,因为通过&funfun获取到的都是函数的地址(0x400586),同样的 f,*f,f1,*f1都是执行函数fun的地址(0x400586),所以调用方式选取一个即可: f(3), (*f)(3), f1(3), (*f1)(3);
也可以使用typedef定义函数指针,如FUNC,这样在申明函数指针变量时写法比上述方法更简洁,同样funcfunc1两种声明方式也是等价的,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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容