【问题标题】:Incompatible function pointer types when making array of pointers制作指针数组时不兼容的函数指针类型
【发布时间】: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)。)

标签: c pointers gcc


【解决方案1】:
const void (*command_functions[]) (char **) = { /*...*/ };

上面复制的已发布代码将command_functions 声明为指向返回const void 的函数的指针数组(这是合法的,尽管不常见,例如参见this answer)。

要将 command_functions 声明为指向返回 void 的函数的 const 指针数组,请改用以下代码。

void (*const command_functions[]) (char **) = { /*...*/ };

【讨论】:

  • 警告在 IDE 中消失并编译。谢谢你的澄清!
猜你喜欢
  • 1970-01-01
  • 2020-10-11
  • 2013-11-06
  • 2018-11-23
  • 2016-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多