我有一个未分类的字典文件,名为“dict.txt”。 我已经设法将文件中的单词放入数组中,而且我使用的 qsort() 似乎也工作正常(也就是说,数组已排序)。
当我调用 bsearch() 时出现问题, 程序崩溃,我的问题是:
为什么会这样?
我使用 gcc 进行编译,不使用任何类型的 IDE,所以我没有任何调试器,也不知道如何使用(目前)。
我很清楚这里提供的代码可能包含几个问题。
那是因为我对 c 很陌生,而且我的背景主要是 Java(尽管有相似之处,但这似乎是一个缺点,因为我已经习惯了 OO 而 c 显然不是 OO)。
如有任何建议,我们将不胜感激。
int strcmp_mod(const void *p1, const void *p2) {
return strcmp(* (char * const *) p1, * (char * const *) p2);
}
int main(void) {
int size, i;
char **words;
char *pItem;
char *key = "fight";
char* buf = load_file("dict.txt"); if (buf == NULL) return 1;
size = count_words(buf);
words = (char**)malloc((size+1) * sizeof(char*));
for (i=0; i<size; i++) {
words[i] = (char*)malloc(80 * sizeof(char));
}
copy_words_to_lower(buf, words, size);
words[size] = '\0';
qsort(words, size, sizeof(char*), strcmp_mod);
for (i=0; i<size; i++) {
printf("%s\n", words[i]);
}
pItem = (char *) bsearch(key, words, size, sizeof(char*), strcmp_mod);
if (pItem!=NULL)
printf ("%s is in the array.\n", pItem);
else
printf ("%s is not in the array.\n", key);
return 0;
}
最佳答案
尝试为 bsearch
提供 key
的地址。
关于c - 为什么调用 bsearch() 会使呈现的程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1813617/