c - 为什么调用 bsearch() 会使呈现的程序崩溃?

标签 c sorting debugging bsearch

我有一个未分类的字典文件,名为“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/

相关文章:

c++ - Visual C++ - 检测程序是否加载到可视化调试器中

c++ - 调试断言失败 : _CrtIsValidHeapPointer(block)

c - 在创建霍夫曼树时哪个节点在增加权重时向左或向右

c - shmget中没有这样的文件或目录错误

c - 在 cygwin 中重新实现 mremap,新空间不可写

c# - 字典或列表

c - 在 C 中包含 Guards 语法

python - 在 Python 中合并和排序日志文件

c - 选择排序与链表的

java - 方法没有抛出 UnsupportedOperationException,尽管它应该抛出