C语言中多参数函数从不兼容的指针类型初始化

jtjikinw  于 2023-03-01  发布在  其他
关注(0)|答案(2)|浏览(136)

我试图声明一个函数来使用*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
};

寻找一种更优雅的方法来参数化它

xxb16uws

xxb16uws1#

声明部分很容易通过显式强制转换来解决:

typedef int cmd_func(char**);
int (*builtin_func[]) (char**) = {
  &sh_cd,
  &sh_path,
  &sh_exit,
  (cmd_func *)& sh_redirection
};

这种类型的强制类型转换在C中很常见,当你必须在结构体中存储函数指针时。简单地说,现在困难的部分是正确地使用函数指针,也就是说将预期数量的参数传递给每个函数...

nzk0hqpo

nzk0hqpo2#

这是更好的other one的替代答案。
目前C语言允许声明没有原型的函数类型,即参数的类型列表。因此,你可以:

int (*builtin_func[]) () = {
&sh_cd,
&sh_path,
&sh_exit,
&sh_redirection
};

最大的缺点是您会丢失任何类型的参数检查。
此外,还有其他更微妙和相当危险的问题。当通过这种指针类型调用函数时,必须注意调用参数会进行默认参数升级,从而改变某些参数的类型。例如char升级为intfloat升级为double
因此,你不能使用带charfloat等参数的函数来初始化builtin_func中的条目。编译器 * 可能 * 警告你,但也可能不警告你。

相关问题