How does the compare function in qsort work?

前端 未结 6 1221
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 03:36

I found this sample code online, which explains how the qsort function works. I could not understand what the compare function returns.

#include         


        
6条回答
  •  被撕碎了的回忆
    2020-12-06 03:58

    int cmpfunc (const void * a, const void * b) //what is it returning?
    {
       return ( *(int*)a - *(int*)b ); //What is a and b?
    }
    

    Is equivalent to:

    int cmpfunc (const void * a, const void * b) //what is it returning?
    {
       // qsort() passes in `void*` types because it can't know the actual types being sorted
       // convert those pointers to pointers to int and deref them to get the actual int values
    
       int val1 = *(int*)a;
       int val2 = *(int*)b;
    
       // qsort() expects the comparison function to return:
       // 
       //    a negative result if val1 < val2
       //    0 if val1 == val2
       //    a positive result if val1 > val2
    
       return ( val1 - val2 ); 
    }
    

提交回复
热议问题