4

我有一个看起来像这样的结构:

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

形成一个有序数组:

dictionary_t dictionary[100];

我想使用 bsearch() 在该数组中搜索字符串并获取指向该结构的指针。到目前为止,这已经奏效:

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

但是,这有点小技巧,并且仅在字符串恰好是结构的第一个成员时才有效。在结构数组中查找字符串并返回指向该结构的指针的更好方法是什么?

4

1 回答 1

3

You should implement your own comparator function and pass it in. The most important (non-trivial) thing to keep in mind here is that according to the standard,

The implementation shall ensure that the first argument is always a pointer to the key.

This means that you can write a comparator that compares a string such as target and a dictionary_t object. Here is 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));
}

You would then pass it by name as a normal function pointer to bsearch:

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

Note that target does not need to have its address passed in since it is no longer mocking a struct.

In case you are wondering, sizeof(((dictionary_t *)0)->word) is an idiomatic way of getting the size of word in dictionary_t. You could also do sizeof(dictionary[0].word) or define a constant equal to 30. It comes from here.

于 2017-05-09T14:47:48.350 回答