函数指针相关知识

一,函数指针定义

   函数名和数组名一样都是地址,函数名存储在代码区,由于是个常量,不能进行修改,要赋值给一个函数指针变量。

函数指针定义例如:int maxValue(int a,int b)    int (*p)(int a,int b) =NULL;  p 是变量,除了之外的是类型。

使用: p = maxValue;指针可以当函数用

typedef int(*p)(int a,int b) 为int (*)(int ,int)这个类型重新定义为p;

//    int  maxValue(int a, int b);

//    int  p(int a, int b);函数

//    int *p(int a,int b)) function 返回值为 int *的函数

//    int (*p)(int a, int b)   //p就是一个函数指针变量


  //  int (*p)(int, int);  表示定义一个返回值为int 并且有两个int型的参数的函数指针,任何与其格式一致的函数都可以将首地址保持在指针变量p中。

//    int (*p)(int, int);

//    p = sumValue;

//    int sum = p(8, 9);

//    printf("p  --> %p\t\tsumValue --> %p\n", p,sumValue);

//    //当函数指针变量P保存了函数sumValue的首地址后,就可以与函数名sumValue有等效代换的作用,函数调用时用函数名与用函数指针变量,效果一样。

//    int result1 = sumValue(3, 5);

//    int result2 = p(3, 5);

//    printf("result1 = %d\n",result1);

//    printf("result2 = %d\n",result2);


二 函数回调

int  value = getValue(3,5,maxValue);

getValue 执行的过程中再调用(回调)MaxValue;


三 动态排序。四  函数返回值是函数指针

排序需求不定,按照姓名?成绩?年龄?

把决定排序方式的重要语句封装成函数,然后调用。

typedef BOOL (*compare)(int, int);

void bubbleSort(int *array, int count,compare cmp);

void bubbleSort(int *array, int count, compare cmp){


    for (int i = 0; i < count - 1; i++) {

        for (int j = 0; j < count - i - 1; j++) {

            if (cmp(array[j], array[j + 1])) {

                int temp = array[j];

                array[j] = array[j + 1];

                array[j + 1] = temp;

            }

        }

    }

}

typedef struct functionList{

    char *funcName; //函数名称字符串

    compare function; //函数指针变量

    

}functionList;


BOOL ascending(int a,int b);

BOOL ascending(int a,int b){


    return  a >  b ? YES : NO;

}

BOOL descending(int a,int b);

BOOL descending(int a,int b){

    

    return  a <  b ? YES : NO;

}

void printArray(int *array, int count);

void printArray(int *array, int count){


    for (int i = 0; i < count; i++) {

        printf("%d ", array[i]);

    }

    printf("\n");

}

functionList list[2] = {{"asc", ascending}, {"desc", descending}};

compare getFuntionByName(char *name);

compare getFuntionByName(char *name){


    for (int i = 0; i < 2; i++) {

        int result = strcmp(list[i].funcName, name);

        if (result) {

            return list[i].function;

        }

    }

    return NULL;

}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值