qsort实现结构体排序
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct stu
{
char name[20];
int age;
};
int cmp_by_name(void* p1, void* p2)
{
return strcmp(((struct stu*)p1)->name, ((struct stu*)p2)->name);
}
void print(struct stu arr[], int k)
{
int i = 0;
for (i = 0;i < k;i++)
{
printf("%s ", arr[i]);
}
printf("\n");
}
void test()
{
struct stu arr[3] = { {"zhangsan",20}, {"lisi",19} ,{"wamgwu",31}};
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr,sz ,sizeof(arr[0]), cmp_by_name);
print(arr,sz);
}
int main()
{
test();
return 0;
}
如果对你有帮助的话就请点个赞吧