Bsearch () - Search for a string in an array of structures

I have a structure that looks like this:

typedef struct dictionary_t{
    char word[30];
    int foo;
    int bar;
} dictionary_t;

      

Which forms an ordered array:

dictionary_t dictionary[100];

      

I would like to find this array for a string using bsearch () and get a pointer to the structure. So far this has worked:

dictionary_t* result;
char target[30] = "target";
result = bsearch(&target, dictionary, dict_length, sizeof(dictionary_t), (int(*)(const void*,const void*)) strcmp);

      

However, this is a bit of a hack and only works because the string is the first member of the structure. What would be the best way to find a string in an array of structures and return a pointer to the structure?

+3


source to share


1 answer


You have to implement your own comparator function and pass it. The most important (non-trivial) thing to remember is that according to the standard ,

An implementation must ensure that the first argument is always a pointer to a key.

This means that you can write a comparator that compares a string like target

and dictionary_t

. Here's a simple function that compares your stucts to a string:

int compare_string_to_dict(const void *s, const void *d) {
    return strncmp(s, ((const dictionary_t *)d)->word, sizeof(((dictionary_t *)0)->word));
}

      



Then you pass it by name like a normal function pointer to bsearch

:

result = bsearch(target, dictionary, dict_length, sizeof(dictionary_t), compare_string_to_dict);

      

Note that you target

don't need to pass your address as it no longer mocks the structure.

If you're wondering, sizeof(((dictionary_t *)0)->word)

this is the idiomatic way to get the size word

in dictionary_t

. You can also make sizeof(dictionary[0].word)

or define a constant equal to 30. It comes from here .

+2


source







All Articles