bsearch和struct(自定义类型)
我有一个像这样的数组:
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()
函数不正确。从这里 :
比较器比较两个元素的函数。 该function应遵循以下原型:
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*
。
您正在传递一个名为str
的变量作为您的键,但在比较函数中,您将其视为INSTR
。 如果你的键是一个字符串,那么a
实际上应该是指向它的指针,你应该使用它
return strcmp(a, bb->str);
这是基于str
实际上是一个字符串的假设,但我们不能确定没有看到它声明(我猜它是除非你有一些相当不寻常的命名约定)。
编辑:
根据更新,它是一个字符串。
comp
函数的第一个参数将是您作为bsearch
的第一个参数传递的参数,而不是INSTR
。 您的比较函数应该采取相应的行
int comp(const void *a, const void *b) { const char* str = (const char*)a; const INSTR *bb = (INSTR*)b; // if I "return 0;" here i get no error. return strcmp(str, bb->str); }