Trouble using bsearch with an array of strings

折月煮酒 提交于 2019-12-04 09:21:57

Since you are using an array of const char *, bsearch() will pass to the comparison function a pointer to those elements. In other words, it will receive const char * const * in its second argument.

int myStrCmp(const void *s1, const void *s2) {
  const char *key = s1;
  const char * const *arg = s2;
  printf("myStrCmp: s1(%p): %s, s2(%p): %s\n", s1, key, s2, *arg);
  return strcmp(key, *arg);
}

Your state name (or key) needs to be a pointer to a pointer. Didn't have to add/remove constanywhere. myStrCmpneeds to dereference by one to compare the strings. The code below does what you want I think. Please let me know if not, thanks.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


const char *stateNames[] = {"Alabama", "Alaska", "Arizona", "Arkansas","California", "Colorado", "Connecticut", "Delaware", "Florida","Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "Washington DC", "West Virginia", "Wisconsin", "Wyoming"};

int myStrCmp(const void *s1, const void *s2) {
    printf("myStrCmp: s1(%p): %s, s2(%p): %s\n", s1, *(char **)s1, s2, *(char**)s2);
    return strcmp(*(char **) s1, *(char **) s2);
}

int determineState(char *state) {
    printf("state: %s\n", state);

    for(int i = 0; i < 51; i++)
        printf("stateNames[%i](%p): %s\n", i, &(stateNames[i]), stateNames[i]);

    char **found = (char **) bsearch(&state, stateNames, 51, sizeof(char *), myStrCmp );

    if(found == NULL){
        return -1;
    } else {
        printf("Found it!: %s\n", *found);

    }

    return 0;
}

int main(int argc, const char * argv[]) {
    determineState("Alabama");

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!