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.
A few things:
const char**
in this case. So pcommand
should be const char**
and accessed/printed as *pcommand
.command
).g
or g_
.Your code seems standard compliant.