You also can't use strcmp directly.
The compar routine is expected to have two arguments which
point to the key
object and to an array member, in that order, and should return an integer less than, equal to, or greater than zero if the key object is found, respectively, to be less than, to match, or be greater
than the array member.
The compare function gets pointers to pointers.
So it needs a simple wrapper to do one level of dereferencing to get to something strcmp can use.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN(x) (sizeof (x) / sizeof (x[0]))
char *tab[] = {
"alfa",
"beta",
"delta",
"epsilon",
"gama",
"zeta",
};
int mycmp(const void *a, const void *b) {
const char * const *pa = a;
const char * const *pb = b;
return strcmp(*pa,*pb);
}
int
main(int argc, char *argv[])
{
char **t;
argc--;
argv++;
if (argc != 1)
return EXIT_FAILURE;
t = bsearch(argv, tab, LEN(tab), sizeof *tab, mycmp);
if (t != NULL)
printf("%s\n", *t);
return EXIT_SUCCESS;
}