2014-09-28 65 views
0

我想使用qsort基於它們的y值對x-y座標結構指針的數組進行排序,但是q sort沒有比較正確的值。我對此感到困惑,任何人都可以看到我做錯了什麼?qsort比較所有的零

排序功能:

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 

有什麼想法發生了什麼?因爲如果你有Coordinate結構,而不是指針Coordinate結構數組的數組

回答

1

你比較函數被寫入。

既然你的陣列指針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; } 
} 
+0

yup。剛剛得到了。謝謝 – Kdawg 2014-09-28 05:06:12