美文网首页
[C指针]函数指针举例:C语言 完整源码

[C指针]函数指针举例:C语言 完整源码

作者: AkuRinbu | 来源:发表于2019-04-18 16:29 被阅读0次

运行结果

运行结果

完整源码

#include <stdio.h>

typedef int (*OP)(int ,int);

int plus(int a,int b) {
    return a+b;
}

int mins(int a,int b) {
    return a-b;
}

int mul(int a,int b) {
    return a*b;
}

int pow(int a,int b) {
    int n = 1;
    for(int i=0;i<b;i++) {
        n *= a;
    }
    return n;
}

void cal(OP op, int a, int b,char * mss) {
    printf("%s(%d,%d)=%d\n",mss,a,b,op(a,b));
}

int main()
{
    int a = 2;
    int b = 5;
    cal(plus,2,5,"plus");
    cal(mins,2,5,"mins");
    cal(mul ,2,5,"mul");
    cal(pow ,2,5,"pow");
    
    return 0;
}
  • typedef int (*OP)(int ,int);
    只要是传入的参数是两个int类型,并且返回值也是int类型的函数,都可叫做是OP类型的,OP是程序员自己取的名字

  • 函数的函数名,是一个地址,是函数所在内存的入口地址,即函数内第一条代码所在内存的地址

参考资料

[习题18]C语言 回调函数:指向函数的指针 int (*POINTER_NAME) = (int a ,int b);
https://www.jianshu.com/p/a63b9575c86a

[C指针]函数指针:保存函数入口地址的指针
https://www.jianshu.com/p/8813b51ae058

[C指针]指针与字符串:函数指针与字符串
https://www.jianshu.com/p/04e4e5609f91

相关文章

网友评论

      本文标题:[C指针]函数指针举例:C语言 完整源码

      本文链接:https://www.haomeiwen.com/subject/ejutgqtx.html