How to use qsort for an array of strings?

前端 未结 3 1985
傲寒
傲寒 2021-01-15 04:45
#include 
#include 
#include 

int sortstring(const void *str1, const void *str2) {
    const char *rec1 = str1;
    c         


        
相关标签:
3条回答
  • 2021-01-15 05:39

    Your comparator is being sent each pair by-address. I.e. they're pointer-to-pointer-to-char.

    Change the comparator to:

    int sortstring( const void *str1, const void *str2 )
    {
        char *const *pp1 = str1;
        char *const *pp2 = str2;
        return strcmp(*pp1, *pp2);
    }
    

    Likewise, your sortutil needs to know the number of items being sorted, as well as pass the correct size of each item. Change that to:

    void sortutil(char* lines[], int count)
    {
        qsort(lines, count, sizeof(*lines), sortstring);
    }
    

    Finally, the call from main() should look like this:

    sortutil(arr, numlines);
    

    That should do it.

    0 讨论(0)
  • 2021-01-15 05:45

    What the compar function gets are pointers to the elements in your array, which in this case, are pointers to char. So the parameters str1 and str2 are actually pointers to pointers to char. You must cast them like this:

    int sortstring( const void *str1, const void *str2 )
    {
        const char *rec1 = *(char**)str1;
        const char *rec2 = *(char**)str2;
        int val = strcmp(rec1, rec2);
    
        return val;
    }
    

    Then you have to use the proper element size in qsort.

    qsort(lines, 200, sizeof(char*), sortstring);
    
    0 讨论(0)
  • 2021-01-15 05:45

    This line is incorrect.

        qsort(lines, 200, sizeof(char), sortstring);
    

    Change it to

        qsort(lines, 200, sizeof(char*), sortstring);
    
    0 讨论(0)
提交回复
热议问题