1那段代码也可以写成如下
struct Student{
....
....
}name
int paixu(const void *a,const void *b)
name aa=*(name*a);
name bb=*(name*b);

 

2那段代码也可以写成这
return aa->score > bb->score ? 1 : -1;//升序排序
------------------------------------------------
return aa->score > bb->score ? -1 : 1;//降序排序

1.“->”:是指针运算符,用于从结构体中提取数据。

如下的aa->score就是从Student中提取出score的值。

2.“ > ? :”:三目运算符

如下的aa中的score < bb中的score ? 1 : -1可以看成:如果aa中的score小于bb中的score就返回1,否则返回-1.

3.qsort函数:

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))

base -- 指向要排序的数组的第一个元素的指针。
nitems -- 由 base 指向的数组中元素的个数。
size -- 数组中每个元素的大小,以字节为单位。
compar -- 用来比较两个元素的函数。

如下用了chucun——第一个元素的指针, 5,——数组中元素的个数, sizeof(chucun[0])——数组中每个元素的大小, paixu——比较函数

4.(const void *a,const void *b)

const:只可读的常量

void*:空类型(即可以是任何类型)

a:一个指针

5.struct Student* aa = (struct Student*)a;

在4中说过,a为空类型无法与同为空类型的b比较,所以我们进行数据转换(具体是转为Student类型),并将装换后的数值存在aa中。类似于 int b =(int)a;

#include<stdio.h>
#include<stdlib.h>
	struct Student {
		int xuehao;
		char name[20];
		float score;
	};1
	int paixu(const void* a, const void* b)
	{
		struct Student* aa = (struct Student*)a;1
		struct Student* bb = (struct Student*)b;1
		return (aa->score < bb->score ? 1 : -1);2
	}
	int main()
	{
		struct Student chucun[5] = { {10101,"Zhang",78},{10103,"Wang",98.5},{10106,"Li",86},{10108,"Ling",73.5},{10110,"Fun",100}};
		qsort(chucun, 5, sizeof(chucun[0]), paixu);
		int i;
		for (i = 0; i < 5; i++)
		{
			printf("%d %s %.2f\n", chucun[i].xuehao, chucun[i].name,chucun[i].score);
		}
		return 0;
	}

Ps:加个关注一起讨论问题!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐