zoukankan      html  css  js  c++  java
  • C语言基础:函数指针 分类: iOS学习 c语言基础 2015-06-10 21:55 15人阅读 评论(0) 收藏

    函数指针:指向函数的指针变量.

    函数名相当于首地址.
    函数指针定义:返回值类型  (*函数指针变量名)(参数类型1,参数类型2,....)=初始值
    函数指针类型:返回值类型  (*)(参数类型1,参数类型2,....)=初始值
    如:int  (*)(int int)  表示返回值是int类型,参数有两个,都为int类型的指针变量类型
    void sayHello(){
    printf("你好!!! ");
    }
    void (*p)()=NULL;   //表示返回值为空,无参数的,函数指针变量名是p的函数指针
    p=sayHello;    //因为函数名就是地址,就是把函数名赋值给函数指针变量p
    函数指针在指向相应地址后可以只用()调用函数

    给函数指针类型起别名
    typedef  返回值(*新类型名)(参数类型1,参数类型2...)
    如:typedef int(*FUN)(int,int)  表示给int (*)(int,int) 起了个别名FUN

    函数回调:用函数指针来调用函数
    如:


    #import <Foundation/Foundation.h>

    //定义一个结构体,使用函数回调实现动态排序(年龄.姓名.分数)

    typedef struct student{

        char name[50];

        int age;

        float score;

    }Student;

    BOOL compareName(Student stu1,Student stu2);  //声明

    BOOL compareName(Student stu1,Student stu2){  //按姓名排序实现

        return strcmp(stu1.name, stu2.name);

    }

    BOOL compareAge(Student stu1,Student stu2);   //声明

    BOOL compareAge(Student stu1,Student stu2){   //按年龄排序实现

        return stu1.age>stu2.age?YES:NO;

    }

    BOOL compareScore(Student stu1,Student stu2);   //声明

    BOOL compareScore(Student stu1,Student stu2){   //按分数排序实现

        return stu1.score>stu2.score?YES:NO;

    }

    void bubbleArray(Student *a,int count,BOOL (*p)(Student,Student));

    void bubbleArray(Student *a,int count,BOOL (*p)(Student,Student)){    //运行时函数,参数:一个指针变量,一个长度,一个函数指针

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

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

                if (p(a[ j ],a[j+1])) {    //由参数函数指针所指向的函数决定按什么类型排序

                    Student temp=a [ j ];

                    a[ j ]=a[j+1];

                    a[j+1]=temp;

                }

            }

        }

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

            printf("%s %d %.2f ",a[ i ].name,a[ i ].age,a[ i ].score);

        }

    }

    int main(int argc, const char * argv[]) {

        Student stuArray[ ]={   //定义一个结构体数组

            {"xijinping",98,80.0},

            {"aobama",75,60.1},

            {"benladeng",55,56.3},

            {"pujing",58,88.6},

            {"chengguan",63,98.0}

        };

        BOOL (*p)(Student,Student)=NULL;    //函数指针初始化

        p=compareAge;     //为函数指针赋值,指向的是函数compareAge的地址

        //    p=compareName;

        //    p=compareScore;

        bubbleArray(stuArray, 5, p);   //调用函数

        return 0;

    }

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Deploy Django in Windows
    Django开发环境配置
    springmvc源码解读
    分布式事务中常见的三种解决方案
    分布式锁总结
    JAVA代码优化
    Mysql(mysql总结)
    树(数据结构二)
    集合(Java总结一)
    centos7.7下docker与k8s安装(DevOps三)
  • 原文地址:https://www.cnblogs.com/shaoting/p/4619828.html
Copyright © 2011-2022 走看看