qsort对cmpstr没有任何帮助

时间:2017-11-15 03:00:37

标签: c sorting qsort

我不确定为什么qsort不会更改我的数组,因为元素不是按字母顺序排列的。有人可以帮我弄清楚我做错了什么。

char **wordlist = malloc(sizeof(char*));
int i, numwords = 0;
wordlist[0] = strdup(words[0]);

for(i = 0; i < wcount; i++)
{
    wordlist = realloc(wordlist, (numwords+1)*sizeof(char *));
    wordlist[numwords] = strdup(words[i]);
    numwords++;
}

printf("Added %d words to the array and they are:\n", numwords);
for(i = 0; i < numwords; i++)
{
    printf("%s\n", wordlist[i]);
}

qsort(wordlist, numwords, sizeof(char *), cmpstr);

for(i = 0; i < numwords; i++)
{
    printf("%s\n", wordlist[i]);
}

int cmpstr(const void* a, const void* b)
{
   const char* aa = (const char*)a;
   const char* bb = (const char*)b;
   return strcmp(aa, bb);
}

1 个答案:

答案 0 :(得分:2)

您的比较错误:

int cmpstr(const void* a, const void* b) {
    char *aa = * (char * const *)a;
    char *bb = * (char * const *)b;
//             ^
//       asterisk here!
//
    return strcmp(aa, bb);
}

ab指针指针

或者:

int cmpstr(const void* a, const void* b) {
    char * const * aa = a;
    char * const * bb = b;
    return strcmp(*aa, *bb);
}

此外,由于您没有free() strdup()提供的内容,因此存在潜在的内存泄漏。您应该删除给定代码中的第3行:

wordlist[0] = strdup(words[0]);