函数指针,使用qsort,进行结构体排序

时间:2022-07-24
本文章向大家介绍函数指针,使用qsort,进行结构体排序,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#include <stdio.h>
#include <stdlib.h>
#define STU_NAME_LEN 16
/*学生信息*/
typedef struct student_tag
{
    char name[STU_NAME_LEN];  //学生姓名
    unsigned int id;          //学生学号
    int score;                //学生成绩
}student_t;
int studentCompare(const void *stu1,const void *stu2)
{
  /*强转成需要比较的数据结构*/
    student_t *value1 = (student_t*)stu1;
    student_t *value2 = (student_t*)stu2;
    return value1->score-value2->score;
}
int main(void)
{
    /*创建三个学生信息*/
    student_t stu1 = {"one",1,99};
    student_t stu2 = {"two",2,77};
    student_t stu3 = {"three",3,88};

    student_t stu[] = {stu1,stu2,stu3};

    /*排序,将studentCompare作为参数传入qsort*/
    qsort((void*)stu,3,sizeof(student_t),studentCompare);
    int loop = 0;

    /**遍历输出*/
    for(loop = 0; loop < 3;loop++)
    {
        printf("name:%s,id:%u,score:%dn",stu[loop].name,stu[loop].id,stu[loop].score);
    }
    return 0;
}

我们创建了一个学生信息结构,结构成员包括名字,学号和成绩。main函数中创建了一个包含三个学生信息的数组,并使用qsort函数对数组按照学生成绩进行排序。qsort函数第四个参数是函数指针,因此我们需要传入一个函数指针,并且这个函数指针的入参是cont void *类型,返回值为int。我们通过前面的学习知道了函数名本身就是指针,因此只需要将我们自己实现的studentCompare作为参数传入即可。

最终运行结果如下:

name:two,id:2,score:77
name:three,id:3,score:88
name:one,id:1,score:99

可以看到,最终学生信息按照分数从低到高输出。