【问题标题】:qsort comparing all zerosqsort 比较全零
【发布时间】:2014-09-28 04:56:50
【问题描述】:

我正在尝试使用 qsort 根据 y 值对 x-y 坐标结构指针数组进行排序,但 q sort 没有比较正确的值。我在这一点上感到困惑,谁能看到我做错了什么?

排序功能:

 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 } 

打电话

79     qsort(pointArray, count, sizeof(Coordinate*), sortFunc);
80     printArray(pointArray, count);

产量

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

知道发生了什么吗?

【问题讨论】:

    标签: c qsort


    【解决方案1】:

    您的比较函数被编写为好像您有一个 Coordinate 结构数组,而不是一个 指针Coordinate 结构的数组。

    由于您有一个 指针Coordinate 结构的数组,比较函数将接收 指向指针Coordinate 结构的指针作为参数。因此,您的比较函数应如下所示

    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; }
    }
    

    【讨论】:

    • 是的。刚得到那个。谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-10-10
    • 2021-04-11
    • 2016-09-08
    • 1970-01-01
    • 2018-03-26
    • 2015-05-22
    • 2019-07-01
    相关资源
    最近更新 更多