简体   繁体   中英

qsort() - sorting an array of strings

Can't seem to find the answer on any question here. Basically I have this line of code:

qsort(Code_Lines, number_of_lines, sizeof(char*), myCmp);

when Code_Lines is a char** - points to an array of char* s when each one contains a string OR pointing to NULL. What I want to do is to sort all of the strings alphabetically when the strings containing NULL will be at the END of the array. Each string within the Code_Lines will be sorted by its 4 first characters (it's unequal in length of each string - and the first four characters are always different - mentioning a number from 0001 to 9999 ), if it's NULL it will just put it in the end of the array. The variable number_of_lines is containing the number of lines (code lines) that are in the array, AKA - number of elements (strings, in this case) in the array. myCmp is my compare function and I wrote it this way:

int myCmp(const void* element1, const void* element2)
{
    int return_value;

    if(!element1) //element1 of them is NULL
    {
        return_value = 1;
    }
    else if(!element2) //element 2 is NULL
    {
        return_value = -1;
    }
    else
    {
        return_value = strncmp(*((char**)element1), *((char**)element2), 4);
    }

    return return_value;
}

Any idea what the problem might be ? The program just crashes there. The function works when the array isn't containing NULL but fails when it does...

In a qsort comparison function, the arguments are pointers to the elements of the array you provided, not the elements themselves. The elements being compared obviously exist, so these pointers can never by NULL by definition. What you want to check is whether a particular element is NULL , not the pointer to element:

int myCmp(const void* element1, const void* element2)
{
    int return_value;
    char * e1 = *(char **) element1;
    char * e2 = *(char **) element2;

    if(!e1) //element1 of them is NULL
    {
        return_value = 1;
    }
    else if(!e2) //element 2 is NULL
    {
        return_value = -1;
    }
    else
    {
        return_value = strncmp(e1, e2, 4);
    }

    return return_value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM