我遇到了一些以前从未见过的 C 语法:
static struct {
char *name;
void (*f)(int a, int b, int c);
} commands[] = {
{ "cmd1", func1 },
{ "cmd2", func2 },
{ "cmd3", func3 },
};
这涉及一个命令解析器,它将用户输入命令与相应的函数之一相匹配,如下所示:
for (int i = 0; i < N; ++i) {
if (strcmp(args[0], commands[i].name) == 0) {
(commands[i].f)(a, b, c);
return;
}
}
我什至无法在谷歌上搜索帮助,因为我不知道这种结构叫什么,而且看起来有些深奥。
我想要做的是创建更多这样的结构,然后将循环放入一个单独的函数中并将其概括,以便我可以根据某些条件向函数传递不同的结构。但是我不知道如何将结构分配给变量并将它们传递给函数。
最佳答案
What I want to do is create more of these structs, then put the loop into a separate function and generalize it
然后您可能想为该结构指定一个名称(标签),如下所示:
struct command {
const char *name; // notice the `const', by the way!
void (*f)(int a, int b, int c);
};
并隔离类型定义和变量声明:
struct command commands[] = {
{ "cmd1", func1 },
{ "cmd2", func2 },
{ "cmd3", func3 },
};
诀窍在于,struct
关键字会立即创建一个类型(只要遇到结构定义中的右大括号),因此您不必有一个单独的 struct
声明和该结构类型的变量的定义,这些可以合并 - 这就是您发布的代码的作用。
关于c - 请帮助我理解 C 中不熟悉的结构语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19887163/