Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 823
Fabricio Avatar asked May 14 '26 04:05

Fabricio


1 Answers

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*.

like image 93
hmjd Avatar answered May 15 '26 17:05

hmjd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!