Search code examples
carrayspointerscharbsearch

bsearch, array of const chars and pointer arthmetic


I want to use bsearch with array of const chars in order to determine index in this array. Here is the code:

enum _command {dodaj, koniec, usun, wczytaj, wczytajwszystko, zapisz, zapiszwszystko};
const char *_command_s[] = {"dodaj", "koniec", "usun", "wczytaj", "wczytajwszystko", "zapisz", "zapiszwszystko"};
int
const_strcmp(const void *s1, const void *s2) {
    const char *key = s1;
    const char * const *arg = s2;
    return strcmp(key, *arg);
}

int main() {
char *pcommand. command[100];/*and other vars*/
pcommand = (char *)bsearch(command, _command_s, COUNT(_command_s), \
            sizeof(char *), (int (*)(const void *, const void *))const_strcmp);


if (pcommand == NULL) 
        fputs_state = fputs(PROMPT, stdout);
else {
    switch ((enum _command)((pcommand - (char *)_command_s)/sizeof(char *))) {
        case dodaj:
        (do something)

It's working on GNU/Linux/gcc but I'm not sure is it ANSI standards-compliant and would it work properly on others compilers. Do you think I can use this this way or maybe you have any better proposals for solving this task.


Solution

  • A few things:

    • compare func arguments are actually const char**, you treat one of them wrong (key).
    • bsearch returns const char** in this case. So pcommand should be const char** and accessed/printed as *pcommand.
    • you call bsearch with an uninitialized variable as the first parameter (command).
    • Using so many variables with similar names is confusing to say the least. At least prefix the globals with g or g_.

    Your code seems standard compliant.