我试图声明一个函数来使用*builtin_func[]
中的参数化数组,但是其中一个函数接受两个参数而不是一个参数(sh_redirection
)。
int sh_cd(char **args);
int sh_exit(char **args);
int sh_path(char **args);
int sh_redirection(char **args, int idx);
char ERROR_MESSAGE[128] = "An error has occurred\n";
extern char **environ;
/*
List of builtin commands, followed by their corresponding functions.
*/
char *builtin_str[] = {
"cd",
"path",
"exit",
">"
};
int (*builtin_func[]) (char **) = {
&sh_cd,
&sh_path,
&sh_exit,
&sh_redirection
};
我得到的错误是:
error: initialization from incompatible pointer type [-Werror=incompatible-pointer-types]
&sh_redirection
我尝试将*builtin_func
更改为
int (*builtin_func[]) (char **, int) = {
&sh_cd,
&sh_path,
&sh_exit,
&sh_redirection
};
寻找一种更优雅的方法来参数化它
2条答案
按热度按时间xxb16uws1#
声明部分很容易通过显式强制转换来解决:
这种类型的强制类型转换在C中很常见,当你必须在结构体中存储函数指针时。简单地说,现在困难的部分是正确地使用函数指针,也就是说将预期数量的参数传递给每个函数...
nzk0hqpo2#
这是更好的other one的替代答案。
目前C语言允许声明没有原型的函数类型,即参数的类型列表。因此,你可以:
最大的缺点是您会丢失任何类型的参数检查。
此外,还有其他更微妙和相当危险的问题。当通过这种指针类型调用函数时,必须注意调用参数会进行默认参数升级,从而改变某些参数的类型。例如
char
升级为int
或float
升级为double
。因此,你不能使用带
char
、float
等参数的函数来初始化builtin_func
中的条目。编译器 * 可能 * 警告你,但也可能不警告你。