gpt4 book ai didi

c - bsearch 和结构(自定义类型)

转载 作者:太空狗 更新时间:2023-10-29 15:59:25 24 4
gpt4 key购买 nike

我有一个这样的数组:

typedef struct INSTR
{
char* str;
int argc;
} INSTR;
const static INSTR instructions[] = { {"blue",1}, {"green",2} };

然后我尝试执行 bsearch,但我收到了 Segmentation fault 消息:

int comp(const void *a, const void *b)
{
const INSTR *aa = (INSTR*)a;
const INSTR *bb = (INSTR*)b;
// if I "return 0;" here i get no error.
return strcmp(aa->str, bb->str);
}

.

char *str = get_string(src_buff, size);
bsearch(str, instructions,
sizeof(instructions) / sizeof(instructions[0]),
sizeof(instructions[0]), comp);

最佳答案

comp() 函数不正确。来自 here :

comparator Function that compares two elements. The function shall follow this prototype:

int comparator ( const void * pkey, const void * pelem );
The function must accept two parameters: the first one pointing to the
key object, and the second one to an element of the array, both
type-casted as void*. The function should cast the parameters back to
some data type and compare them.

comp() 的第一个参数是 const char*,而不是 INSTR*

更改为:

int comp(const void *a, const void *b)
{
const INSTR *bb = (INSTR*)b;
return strcmp((const char*)a, bb->str);
}

或者,将 key 更改为 INSTR* 而不是 const char*

关于c - bsearch 和结构(自定义类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9185007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com