C qsort比较所有零
我试图使用qsort根据x-y坐标结构指针的y值对其数组进行排序,但qsort没有比较正确的值。我在这一点上感到困惑,有人能看出我做错了什么吗 排序功能:C qsort比较所有零,c,qsort,C,Qsort,我试图使用qsort根据x-y坐标结构指针的y值对其数组进行排序,但qsort没有比较正确的值。我在这一点上感到困惑,有人能看出我做错了什么吗 排序功能: 23 int sortFunc(const void * firsti, const void * secondi){ 24 25 const Coordinate* first = firsti; 26 const Coordinate* second = secondi; 27 28
23 int sortFunc(const void * firsti, const void * secondi){
24
25 const Coordinate* first = firsti;
26 const Coordinate* second = secondi;
27
28 printf("Comparing %f & %f\n", first->y, second->y);
29 if(first->y < second->y){ return 1;}
30 else if(first->y == second->y){ return 0; }
31 else{ return -1; }
32
33 }
13 void printArray(Coordinate * array[], int size){
14
15 int x;
16 for(x=0; x < size; x++){
17 printf("Point %i : %f | %f\n", x, array[x]->x, array[x]->y);
18 }
19
20 }
屈服
Comparing 0.000000 & 0.000000
Comparing 0.000000 & 0.000000
Comparing 0.000000 & 0.000000
Comparing 0.000000 & 0.000000
Comparing 0.000000 & 0.000000
Comparing 0.000000 & 0.000000
Comparing 0.000000 & 0.000000
Point 0 : 103.253334 | -12.472327
Point 1 : -3.283118 | -3.101071
Point 2 : 9.289474 | -0.459975
Point 3 : 14.029107 | -11.844076
Point 4 : -6.465595 | 14.704790
Point 5 : -5.764663 | 8.882765
你知道发生了什么吗?你的比较函数是这样写的,好像你有一个
坐标
结构的数组,而不是指向坐标
结构的指针数组
由于您有一个指向坐标
结构的指针数组,因此比较函数将接收指向坐标
结构的指针作为参数。因此,您的比较函数应该如下所示
int sortFunc(const void * firsti, const void * secondi)
{
const Coordinate* const* first = firsti;
const Coordinate* const* second = secondi;
if((*first)->y < (*second)->y){ return 1;}
else if((*first)->y == (*second)->y){ return 0; }
else{ return -1; }
}
int-sortFunc(const-void*firsti,const-void*secondi)
{
常数坐标*const*first=firsti;
常数坐标*常数*秒=秒;
如果((*first)->y<(*second)->y{return 1;}
else如果((*first)->y==(*second)->y{return 0;}
else{return-1;}
}
是的。我明白了。谢谢
int sortFunc(const void * firsti, const void * secondi)
{
const Coordinate* const* first = firsti;
const Coordinate* const* second = secondi;
if((*first)->y < (*second)->y){ return 1;}
else if((*first)->y == (*second)->y){ return 0; }
else{ return -1; }
}