我有一个像这样的数组:
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);
The comp()
函数不正确。来自here http://www.cplusplus.com/reference/clibrary/cstdlib/bsearch/:
比较器
比较两个元素的函数。该函数应遵循以下原型:
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()
is a const char*
, not a 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*
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)