gpt4 book ai didi

c - 函数指针数组

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:57 25 4
gpt4 key购买 nike

在这个代码示例中是否可以用函数指针数组替换所有这些“if, else if ...”?

  if (strncmp(buff, "ls\n", 3) == 0)
my_ls();
else if (strncmp(buff, "cd\n", 3) == 0)
my_cd();
else if (strncmp(buff, "user\n", 5) == 0)
my_user();
else if (strncmp(buff, "pwd\n", 4) == 0)
my_pwd();
else if (strncmp(buff, "quit\n", 5) == 0)
my_quit();

我想得到这样的东西:

void (*tab[5]) (void);

tab[0] = &my_ls;
tab[1] = &my_cd;
tab[2] = &my_user;
tab[3] = &my_pwd;
tab[4] = &my_quit;

最佳答案

我创建了一个代码来说明您想要做什么,因为它非常有趣。

#include <stdio.h>
#include <string.h>

// your functions
void my_ls() { puts("fun:my_ls") ;}
void my_cd() { puts("fun:my_cd") ;}
void my_user(){ puts("fun:my_user");}
void my_pwd() { puts("fun:my_pwd") ;}
void my_quit(){ puts("fun:my_quit");}


int main(int argc, char const *argv[])
{
char* buff="ls\n"; // the string you have to compare

void (*tab[5]) (void)={my_ls,my_cd,my_user,my_pwd,my_quit};
char *names[5]={"ls\n","cd\n","user\n","pwd\n","quit\n"};

int i;
for (i=0; i<5; i++)
{
if(strncmp(buff,names[i],strlen(names[i]) )==0){
tab[i]();
return 0;
}
}
return 0;
}

还有其他的写法。实际上 my_function&my_function 是一样的,因为函数名单独被转换为函数的地址。此外 tab[i]() 等同于 (*tab[i])()...这些都是奇怪的行为,但我认为它是由 C 标准指定的

关于c - 函数指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29237670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com