Search code examples
cpointersbsearch

bsearch and struct (custom type)


I have an array like this:

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

then I tried to do a bsearch, but I'm getting Segmentation fault message:

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

Solution

  • The comp() function is incorrect.From 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.
    

    The first argument to your comp() is a const char*, not a INSTR*.

    Change to:

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

    Or, change the key to be a INSTR* instead of const char*.