需要帮助的qsort使用与结构的数组 [英] Need help using qsort with an array of structs
本文介绍了需要帮助的qsort使用与结构的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在,我已经看到了各种各样的例子,但我不明白他们的意思。
Now, I have seen various examples, but I don't get what they mean.
下面是我的结构
typedef struct profile{
char gender[1];
double soc;
. . .
} PROFILE;
其中SOC是我要通过以下排序的社会安全号码。
where soc is social security number that I'm going to be sorting by.
我知道你需要一个比较功能,但我不知道如何来与我所需要的确切的事情。
I know you need a compare function, but I don't know how to come up with the exact thing I need.
推荐答案
下面是一个使用的qsort对于结构的C中的数组
Here is an example of using qsort for an array of structs in C
/* qsort example */
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int price;
int id;
}order;
order list[6];
int i=0;
int compare (const void * a, const void * b)
{
order *orderA = (order *)a;
order *orderB = (order *)b;
return ( orderB->price - orderA->price );
}
int main ()
{
srand ( time(NULL) );
printf("Before sorting\n");
for(i=0; i<6; i++){
list[i].price = rand()%10;
list[i].id = i;
printf ("Order id = %d Price = %d \n",list[i].id, list[i].price);
}
printf("AFTER sorting\n");
int n;
qsort (list, 6, sizeof(order), compare);
for (n=0; n<6; n++)
printf ("Order id = %d Price = %d \n",list[n].id, list[n].price);
return 0;
}
希望它能帮助
卡捷琳娜季米特里斯·
(所有关于pitsi)
(all regards to pitsi)
这篇关于需要帮助的qsort使用与结构的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文