3

我有一个这样的数组:

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);
4

3 回答 3

3

您正在传递一个名为str您的键的变量,但在比较函数中您将其视为INSTR. 如果你的键是一个字符串,那么a实际上应该是一个指向它的指针,你应该使用

return strcmp(a, bb->str);

这是基于str实际上是一个字符串的假设,但我们不能确定没有看到它声明(我猜它是,除非你有一些相当不寻常的命名约定)。

编辑:

基于更新它一个字符串。

于 2012-02-07T22:38:33.197 回答
3

comp()功能不正确。从这里

比较器 比较两个元素的函数。该函数应遵循此原型:

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()是 a const char*,而不是 a INSTR*

改成:

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

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

于 2012-02-07T22:39:42.093 回答
2

函数的第一个参数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);
}
于 2012-02-07T22:39:46.603 回答