如何在C语言的数组结构中使用qsort()
我试图使用qsort()对结构中的价格进行排序。排序后,结构中的一个元素(test)变为0。你能告诉我为什么以及如何解决这个问题吗 谢谢如何在C语言的数组结构中使用qsort(),c,qsort,C,Qsort,我试图使用qsort()对结构中的价格进行排序。排序后,结构中的一个元素(test)变为0。你能告诉我为什么以及如何解决这个问题吗 谢谢 #include <stdio.h> #include <stdlib.h> typedef struct { int price; int test; int id; } order; order list[10]; int i = 0; int compare (const void * a, const
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int price;
int test;
int id;
} order;
order list[10];
int i = 0;
int compare (const void * a, const void * b)
{
order *orderA = (order *)a;
order *orderB = (order *)b;
return ( orderA->price - orderB->price );
}
int main ()
{
srand ( time(NULL) );
printf("Before sorting\n");
for(i=0; i<10; i++){
list[i].price = rand()%10;
list[i].test = rand()%10;
list[i].id = i;
printf ("Order id = %d Price = %d Test = %d\n",list[i].id, list[i].price, list[i].test);
}
printf("AFTER sorting\n");
int n;
qsort (list, 6, sizeof(order), compare);
for (n=0; n<10; n++)
printf ("Order id = %d Price = %d Test = %d\n",list[n].id, list[n].price, list[i].test);
return 0;
}
#包括
#包括
类型定义结构{
国际价格;
智力测验;
int-id;
}秩序;
订单清单[10];
int i=0;
整数比较(常数无效*a,常数无效*b)
{
订单*订单a=(订单*)a;
订单*订单b=(订单*)b;
退货(订单A->价格-订单B->价格);
}
int main()
{
srand(时间(空));
printf(“排序前”);
对于(i=0;i排序后,改变
printf ("Order id = %d Price = %d Test = %d\n",list[n].id, list[n].price, list[i].test);
到
您只对前6个元素进行排序。问题已解决。注意:要避免int
溢出并处理所有int
,请使用(orderA->price>orderB->price)-(orderA->priceprice)
而不是orderA->price-orderB->price
一旦将i
的声明移动为第一个for循环的整数,问题就很容易出现。
printf ("Order id = %d Price = %d Test = %d\n",list[n].id, list[n].price, list[n].test);