10、函数指针

来源:互联网 发布:淘宝查排名工具 编辑:程序博客网 时间:2024/05/22 06:43

函数指针定义

    int maxValue(int a,int b)       {            return a>b?a:b;       }  

函数名和数组名⼀样是地址!

 int maxValue(int a,int b)       int (*p)(int a,int b)=NULL;      //p是变量,其它是类型(通常没有形参a,b)  

函数指针使⽤

p = maxValue;   //赋值函数名  int m = p(3,5);//指针可当函数⽤  

函数回调

    //函数指针做参数      int getValue(int a,int b, int (*p)(int,int));      //getValue是函数名      //int (*p)(int,int)是函数指针,作为函数的参数  

回调过程:函数名做参数传递
回调过程


动态排序

用于无法预测的需求变更

 /*      有30个学⽣需要排序      1.按姓名排      2.按成绩排      3.按年龄排      ….       ⼀周后新需求,按出勤率排?      */      void sortArray(int * array,int count){            for(int i = 0;i < count -1;i++){                for(int j = 0;j< count-i-1;j++){                    if(条件){ //决定排序⽅式的重要语句封装成函数然后在此回调                       交换                   }               }            }       }  

例:int数组动态排序

    typedef BOOL(*PFUN)(int,int);//为函数指针类型起名为PFUN      void sortArray(int * arr,int count,PFUN p);//动态排序函数声明  

函数返回值是函数指针

    PFUN getFunctionByName(char * name);//通过功能名称查找对应的函数      typedef struct nameFunctionPair       {           char name[30];           PFUN function;      }NameFunctionPair;      NameFunctionPair list[3];
功能名 调⽤函数 “max” maxValue “min” minValue “avg” avgValue
    PFUN fun = NULL;      fun = getFunctionByName(“min”)//查找对应函数minValue      //调⽤返回的函数      int value = fun(3,5);
0 0
原创粉丝点击