Bla*_*ter 0 c arrays struct function
我有一个结构数组,格式为:
struct command functions[] = {
{"1", function1},
{"2", function2},
etc....
}
Run Code Online (Sandbox Code Playgroud)
在函数运行(char*函数)中,我检查参数是否等于存储在struct数组中的一个字符串.如果是,我想调用相应的函数.例如,如果传入"1",我调用function1().
这将如何实现?
到目前为止,我有
run(char* function) {
for (int i = 0; i < num_functions; i++) {
if(*function == functions[i]) {
return (*function)();
}
}
}
Run Code Online (Sandbox Code Playgroud)
出现以下错误:
error: invalid operands to binary == (have int and struct command)
error: called object *function is not a function
Run Code Online (Sandbox Code Playgroud)
您的代码有几个问题似乎导致错误,但遗憾的是您还没有足够的帖子让我完全修复它们.
if(*function == function[i])
使用function[i]
时使用的行functions[i]
(带有"s")char
与a 进行比较struct command
.您可能希望访问包含第一个代码段中显示的字符串的结构成员.strcmp
.char
,这是行不通的.猜测,我想你想要这样的东西:
run(char* function_name) {
for (int i = 0; i < num_functions; i++) {
struct_command function = functions[i];
if(strcmp(function_name, function.name) == 0) {
return function.exec();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这假设你的成员struct command
被命名name
和exec
.