我想将 bsearch 与 const 字符数组一起使用,以确定该数组中的索引。这是代码:
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)
它在 GNU/Linux/gcc 上运行,但我不确定它是否符合 ANSI 标准,并且它是否可以在其他编译器上正常运行。你认为我可以用这种方式吗,或者你有什么更好的建议来解决这个任务。