【发布时间】:2019-04-13 23:25:07
【问题描述】:
我正在尝试在预先排序的数组中查找用户输入字符串。如果我编写自己的二进制搜索函数,则可以正确找到输入。如果我使用 C bsearch,我总是得到一个 NULL 指针。
这是相关代码sn -p:
printf(bsearch(&input, *words, curr_idx + 1, max_len,
(int (*)(const void *, const void *))strcmp) ?
"YES" : "NO");
char input[max_len] 是scanf("%s", input); uppercase(input); 的结果
char **words 是一个预排序的大写字符串数组
int curr_idx 是words 的最大索引
int max_len 是words 中单词的最大长度(以字节为单位)(当前为 18)
我尝试输入我知道在数组中的字符串,以及我知道不在数组中的字符串,并且每种情况都返回一个 NULL 指针。
在gdb中设置断点,检查input和words的内容,似乎没有什么不对的地方:
(gdb) print (char*)input
$5 = 0x7fffffffe610 "STONE"
(gdb) print words[150980]
$6 = 0x555555bf45a0 "STONE"
编辑以添加 MCVE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char **words;
char *dictionary[5] = { "STOMPS", "STONABLE", "STONE", "STONEBOAT", "STONEBOATS" };
int curr_idx = 4;
int max_len = 18;
int compare(const void *a, const void *b)
{
return strcmp((const char *)a, (const char *)b);
}
void uppercase(char *input)
{
char *t = input;
while (*t) {
*t = toupper((unsigned char)*t);
t++;
}
}
int main()
{
words = malloc((curr_idx + 1) * sizeof(char *));
int i;
for (i = 0; i < 5; i++){
// words[i] = malloc(sizeof(char) * max_len);
words[i] = dictionary[i];
}
char input[max_len];
printf("Enter a word: ");
scanf("%s", input);
uppercase(input);
printf(bsearch(input, words, curr_idx + 1, sizeof(*words), compare) ?
"YES\n" :
"NO\n");
}
malloc() 位是不必要的,但旨在尽可能接近地复制原始程序。
【问题讨论】:
-
为什么传递
*words?在printf(bsearch(input, words, curr_idx, sizeof(*words), words_strcmp) != NULL ? "YES" : "NO");那里尝试int words_strcmp(const void *a, const void *b) { return strcmp(a, b) != NULL; }。不要对指针进行类型转换,也不要对函数指针进行类型转换,这是未定义的行为,永远不会起作用(如果它起作用,它总有一天会无缘无故停止)。 -
从不强制转换函数指针。另外,发布minimal reproducible example。
-
@KamilCuk 你的“更正”
words_strcmp是错误的,它需要像 strcmp 一样返回 -/0/+ ;!= NULL是一个错误。 -
您的代码中有 UB。
curr_idx + 1 * sizeof(char *)是curr_idx + (1 * sizeof(char *))