【发布时间】:2018-04-28 03:51:02
【问题描述】:
我不确定为什么 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);
}
【问题讨论】:
-
realloc是错误的。你应该做realloc(wordlist, (numwords+2)*sizeof(char *)); -
请提供
cmpstr()的代码。这很重要。 -
wordlist[0]被分配了两次。wordlist[0] = strdup(words[0]);和第一个wordlist[numwords] = strdup(words[i]);。因此失去了第一次分配。 -
比较函数错误。
a和b指向到const char * -
不是敲门声,但通常当你说“一个经过良好测试的 C 库函数行为错误”时......这不是应该受到指责的函数。您正在寻找
return strcmp (*(char * const *)a, *(char * const *)b);