#include <stdlib.h>
#include <stdio.h>
struct stu
{
char name[20];
int age;
};
int cmp_stu_by_age(const void*e1, const void* e2)
{
return ((struct stu*)e1)->age - ((struct stu*)e2)->age;
}
void test4()
{
struct stu s[3] = { {"张三",20},{"李四",30},{"王五",10} };
int sz = sizeof(s) / sizeof(s[0]);
qsort(s, sz, sizeof(s[0]), cmp_stu_by_age);
int j = 0;
for (j = 0; j < sz; j++)
{
printf("%s %d ", (s+j)->name,(s+j)->age);
}
}
int main()
{
test4();
return 0;
}
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct stu
{
char name[20];
int age;
};
int cmp_stu_by_name(const void* e1, const void* e2)
{
return strcmp(((struct stu*)e1)->name ,((struct stu*)e2)->name);
}
void test5()
{
struct stu s[3] = { {"张三",20},{"李四",30},{"王五",10} };
int sz = sizeof(s) / sizeof(s[0]);
qsort(s, sz, sizeof(s[0]), cmp_stu_by_name);
int j = 0;
for (j = 0; j < sz; j++)
{
printf("%s %d ", (s + j)->name, (s + j)->age);
}
}
int main()
{
test5();
return 0;
}
运行结果
按年龄排序
按名字排序
按名字排序时,用到了strcmp函数,需要在前面加上#include<string.h>