【发布时间】:2021-02-26 14:10:27
【问题描述】:
我正在用 C 创建一个基本的 shell,在使用 gcc 编译时遇到问题:
这是来自我的 IDE 的警告:
[query] incompatible function pointer types initializing 'const void (*)(char **)' with an expression of type 'void (*)(char **)' [-Wincompatible-function-pointer-types]
这是我在尝试使用设置的 json 测试文件发出拉取请求时遇到的错误:
grsh.c:28:48: error: initialization from incompatible pointer type [-Werror=incompatible-pointer-types]
const void (*command_functions[]) (char **) = {&exit_shell, &change_directory, &set_path};
^
grsh.c:28:48: note: (near initialization for 'command_functions[0]')
grsh.c:28:61: error: initialization from incompatible pointer type [-Werror=incompatible-pointer-types]
const void (*command_functions[]) (char **) = {&exit_shell, &change_directory, &set_path};
有问题的特定代码行:
const void (*command_functions[]) (char **) = {&exit_shell, &cd, &set_path};
我会 100% 解决问题,但不确定这里的问题是什么。程序在运行正常编译命令时在 Repl.it 中编译并运行,但在尝试使用 -Werror 和 -Wall 进行编译时遇到问题
希望获得有关如何正确初始化 char 类型的指针数组的一些反馈。
【问题讨论】:
-
exit_shell在哪里以及如何声明? -
请edit您的问题以显示您的代码的更多上下文。最好是一个合适的minimal reproducible example。
-
你不需要
&来获取函数的地址;… = { exit_shell, change_directory, set_path };也可以。除非与sizeof或&一起使用,否则函数指示符会自动转换为其函数的地址。 (由于指示符转换为地址,*exit_shell获取地址并尝试再次使其成为函数,但这会自动转换为地址。所以你可以写***********exit_shell,它仍然是地址。例如,您可以将正弦例程称为(*************sin)(x)。)