A
Amandil
Hi, all.
I'd like to check whether a certain string (one that I got from a
user, or read from a file) is contained in a table of strings. The
format of the table is
char *table[] = { "string1", "string2", "string3", ..., NULL }
I wrote my own function that uses strcmp():
int table_lookup(char *s, char *list[])
{
char *t;
int index = 0;
while ((t = list[index]) != NULL) {
if ( !strcmp(s, t)) {
return 1; /* Found */
}
index++;
}
return 0; /* Not found */
}
I imagine I could use the library function bsearch() to do the same,
and possibly quicker. I do not know, however, what the call to
bsearch() is supposed to look like. A copy of the standard is not very
helpful. I would try
char *t = bsearch(s, list, sizeof list, sizeof (char *), strcmp);
Will this work? Or did I do something wrong? (with faq 13.8 in mind)
I'd like to check whether a certain string (one that I got from a
user, or read from a file) is contained in a table of strings. The
format of the table is
char *table[] = { "string1", "string2", "string3", ..., NULL }
I wrote my own function that uses strcmp():
int table_lookup(char *s, char *list[])
{
char *t;
int index = 0;
while ((t = list[index]) != NULL) {
if ( !strcmp(s, t)) {
return 1; /* Found */
}
index++;
}
return 0; /* Not found */
}
I imagine I could use the library function bsearch() to do the same,
and possibly quicker. I do not know, however, what the call to
bsearch() is supposed to look like. A copy of the standard is not very
helpful. I would try
char *t = bsearch(s, list, sizeof list, sizeof (char *), strcmp);
Will this work? Or did I do something wrong? (with faq 13.8 in mind)