简体   繁体   中英

qsort( ) function in C

I'm trying to use qsort to sort the characters in a single string. It just doesn't seem to work. This is my code.

int compare_function (const void* a, const void* b) 
{
    char f = *((char*)a);
    char s = *((char*)b);
    if (f > s) return  1;
    if (f < s) return -1;
    return 0;
}

int main(int argc, char* argv[]) 
{
    char* str= argv[1];
    /* Originally missing the +1 */
    char* sorted_str = malloc((strlen(str) + 1)*sizeof(char));
    memcpy(sorted_str, str, strlen(str) + 1);

    qsort(sorted_str, sizeof(str)/sizeof(char), sizeof(char), compare_function);

    printf("%s\n", sorted_str);  // Originally str
    free(sorted_str);
    return 0;
}

The output is ? . What do I need to do to fix this?

You are printing your input, not the sorted result. Note the line:

printf("%s\n",str);

should be

printf("%s\n",sorted_str);

The second argument to qsort is not right.

qsort (sorted_str,
       sizeof(str)/sizeof(char),  // sizeof(str) is size of a pointer.
       sizeof(char),
       compare_function);

You need:

qsort (sorted_str,
       strlen(str),
       sizeof(char),
       compare_function);

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