简体   繁体   English

C语言中的qsort()函数

[英]qsort( ) function in C

I'm trying to use qsort to sort the characters in a single string. 我正在尝试使用qsort对单个字符串中的字符进行排序。 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的第二个参数不正确。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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