IOS--C 语言 Lesson Seven 指针函数

1.函数指针变量
// 函数指针的类型确定步骤:
1⃣ 把函数名换成(*函数指针变量名) 函数指针变量不能与函数名重名

   1.  void printfhello();↓
       void (*函数指针变量名)()  无参数型
   2.  int sum (int a ,int b ) 有参数型
       int (*函数指针变量名)(int  ,int );

// 有参数 把参数名去掉 保留参数类型
2.返回值类型
1⃣(*函数指针变量名)(参数类型1,参数类型2…)= 初始值 ;
1.无参数时 两个括号也得有(*函数指针变量名)()
() 调用时叫函数调用符

   void (*hello)() = NULL;
  1. 有参数的函数指针:
 int (*Sum)(int ,int )=NULL;
    hello=printfhello;
    printfhello();
    hello();
  int(*SUM)(int ,int )= sum;// 可以赋空值 也可以赋已有的函数名

正常调用

  int result = sum (3,5);
    printf("%d\n",result);
  1. typedef 原始类型 新类型;
 typedef int (*) (int ,int ) FUN ;error这个错

给函数指针类型起别名

typedef int (*新名字)(参数类型,参数类型);
typedef int (*FUN ) (int ,int );

例题:
1.// 用指针调用函数

void swp(int *a,int *b){
    // 空的也可以
}
///运行时函数
int getValue (int a ,int b,int (*p)(int ,int)){
    return p (a,b);
}

typedef struct student{
    char name[15];
    int age;
    float score;

}Student;

2.//比较学生姓名

//BOOL (*)(Student,Student)
BOOL comparename(Student stu1,Student stu2);
BOOL comparename(Student stu1,Student stu2){
    if (strcmp (stu1.name,stu2.name)>0) {
        return YES;
    }else{
        return NO;
    }//return strcmp(stu1.name ,stu2.name )>0;
}
//BOOL (*)(Student,Student)
BOOL compareage(Student stu1,Student stu2);
BOOL compareage(Student stu1,Student stu2){
    return stu1.age>stu2.age;
 /*   if ( stu1.age>stu2.age) {
        return YES;
    }else{
      return NO;
  */
}
//BOOL (*)(Student,Student)
BOOL comparescore(Student stu1,Student stu2);
BOOL comparenscore(Student stu1,Student stu2){
    return stu1.score>stu2.score;
    /*   if ( stu1.score>stu2.score) {
     return YES;
     }else{
     return NO;
     */
}
void printfArray(Student *stuArray,int count);

void bubbleSortArray(Student *stuArray,int count,BOOL (*p)(Student,Student)){
   for (int i =0; i <count-1; i++) {
        for (int j =0; j < count-i-1; j++) {
//            替换成函数指针,实现函数回调
            if (p(stuArray[j],stuArray[j+1])) {
                Student temp = {0};// 结构体
                temp = stuArray[j];
                stuArray[j]= stuArray[j+1];
                stuArray[j+1]= temp;
            }
        }
   }//遍历数组的函数
    printfArray(stuArray, count);

}
   void printfArray(Student *stuArray,int count){
     for (int i =0; i <count; i++) {
      printf("%s %d %.1f\n",stuArray[i].name,stuArray[i].age,stuArray[i].score);

   }}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值