首页 > 代码库 > 函数指针的用法
函数指针的用法
按结构体字段进行排序
#include<stdio.h>#include<string.h>int compare(void *, void *, int (*)(void *, void *));int orderById(void *, void *);int orderByName(void *, void *);int orderByAge(void *, void *);struct Student { int id; char name[64]; int age; char address[1024];};void arrSort(struct Student *, int, int (*)(void *, void *));int main(void){ struct Student arr[5] = {{ 20140101, "zhangsan", 24, "china.guangzhou" }, { 20140103, "lisi", 28, "USA.ny" }, { 20140102, "wangwu", 18, "UK" }, { 20140110, "zhaoliu", 19, "china.peking" }, { 20140131, "fwy", 27, "china.nc" }}; printf("\n-----------id升序-----------------\n"); arrSort(arr, 5, orderById); printf("\n-----------name升序-----------------\n"); arrSort(arr, 5, orderByName); printf("\n-----------age升序-----------------\n"); arrSort(arr, 5, orderByAge);}//统一比较函数int compare(void * stu, void * stu2, int (*pt)(void *, void *)){ return (*pt)(stu, stu2);}//按Id升序排列int orderById(void * stu, void * stu2){ struct Student s = *((struct Student *)stu); struct Student s2 = *((struct Student *)stu2); return s2.id - s.id;}//按name升序排列int orderByName(void * stu, void * stu2){ struct Student s = *((struct Student *)stu); struct Student s2 = *((struct Student *)stu2); return strcmp(s2.name, s.name);}//按age升序排列int orderByAge(void * stu, void * stu2){ struct Student s = *((struct Student *)stu); struct Student s2 = *((struct Student *)stu2); return s2.age - s.age;}//结构体数组排序void arrSort(struct Student * arr, int size, int (*pt)(void *, void *)){ int i,j; struct Student temp; for(i = 0; i < size -1; i++) { for(j = 0; j < size - 1 - i; j++) { if(compare(&arr[j], &arr[j + 1], pt) < 0) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } for(i = 0; i < size; i++) { printf("%10d %10s %3d %15s\n", arr[i].id, arr[i].name, arr[i].age, arr[i].address); }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。