【问题标题】:bsearch and struct (custom type)bsearch 和 struct(自定义类型)
【发布时间】:2012-02-29 09:32:24
【问题描述】:

我有一个这样的数组:

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

【问题讨论】:

  • str 参数对bsearch 的值是多少?您可以发布产生段错误的可编译示例吗?
  • 我更新了,抱歉。但现在我想我可以看到我的错误了,呵呵。我忘了传递一个结构,而是传递一个字符串。

标签: c pointers bsearch


【解决方案1】:

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

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

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*

【讨论】:

    【解决方案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);
    }
    

    【讨论】:

      【解决方案3】:

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

      return strcmp(a, bb->str);
      

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

      编辑:

      基于更新它一个字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-03
        • 1970-01-01
        • 1970-01-01
        • 2022-09-25
        相关资源
        最近更新 更多