What a horrid solution.
If you're only pointing at two chars (and a \0), then the 4th byte is undefined and you'll never match it with your int comparison.
Not to mention the possibility of bus errors caused by mis-aligned pointers.
Code:
#include <stdio.h>
#include <stdlib.h>
#define ASIZE(x) ((sizeof(x))/(sizeof(x[0])))
/* Stuff to do */
void add ( void ) {
printf( "Hello from add\n" );
}
void edit ( void ) {
printf( "Hello from edit\n" );
}
void delete ( void ) {
printf( "Hello from delete\n" );
}
/* A table of commands and actions */
struct table_tag {
char *cmd;
void (*fn)(void);
} table[] = {
{ "add", add },
{ "edit", edit },
{ "delete", delete },
};
int comp ( const void *a, const void *b ) {
const struct table_tag *pa = a;
const struct table_tag *pb = b;
return strcmp ( pa->cmd, pb->cmd );
}
/* Find a function, given a command */
void searchCommand ( char *cmd ) {
struct table_tag search = { cmd, 0 };
struct table_tag *ans;
ans = bsearch ( &search,
table, ASIZE(table), sizeof(table[0]),
comp );
if ( ans ) {
ans->fn(); /* Do it! */
} else {
printf( "%s not found\n", cmd );
}
}
int main ( ) {
/* Ensure it's sorted, for bsearch to work */
qsort ( table, ASIZE(table), sizeof(table[0]), comp );
/* Practice commands */
searchCommand( "edit" );
searchCommand( "exit" );
return 0;
}