打印功能指针时不兼容的指针类型警告
我正在尝试创建一个函数指针数组,以便我可以使用指针打印函数的输出。 (来自《Effective C》书中的练习。)
#include <stdio.h>
#include <stdlib.h>
int a(void) { return 1; }
int b(void) { return 2; }
int c(void) { return 3; }
int main(void)
{
int(*func_arr)[3] = {&a, &b, &c};
printf("%d\n", (*func_arr)[0]);
}
但是,当我编译它时,我收到警告
starting.c:10:26: warning: incompatible pointer types initializing 'int (*)[3]' with an expression of type
'int (*)(void)' [-Wincompatible-pointer-types]
int(*func_arr)[3] = {&a, &b, &c};
^~
starting.c:10:30: warning: excess elements in scalar initializer
int(*func_arr)[3] = {&a, &b, &c};
^~
并且当我运行程序时,我得到的输出为 -443987883,而它应该只是 1。
有谁知道解决方案为了这?谢谢你!
I am trying to create an array of function pointers, so that I can print out output from the functions by using the pointers. (For an exercise from the Effective C book.)
#include <stdio.h>
#include <stdlib.h>
int a(void) { return 1; }
int b(void) { return 2; }
int c(void) { return 3; }
int main(void)
{
int(*func_arr)[3] = {&a, &b, &c};
printf("%d\n", (*func_arr)[0]);
}
However, when I compile it, I get the warnings
starting.c:10:26: warning: incompatible pointer types initializing 'int (*)[3]' with an expression of type
'int (*)(void)' [-Wincompatible-pointer-types]
int(*func_arr)[3] = {&a, &b, &c};
^~
starting.c:10:30: warning: excess elements in scalar initializer
int(*func_arr)[3] = {&a, &b, &c};
^~
And, when I run the program, I get an output of -443987883, while it should just be 1.
Does anyone know the solution for this? Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该声明
声明了一个指向数组类型
int[3]
的指针。因此,声明了一个指针类型的标量对象,您尝试使用大括号括起来的初始值设定项列表来初始化该对象,其中包含多个不兼容指针类型的初始值设定项。
相反,您需要编写
用作初始值设定项的函数指示符隐式转换为指向函数的指针。
因此,不需要像
&a
那样编写,尽管这样的表达式也可以有效地用作初始值设定项。为了简化数组声明,您可以为函数指针类型引入一个类型化名称。
例如
现在数组声明可以如下所示
并且要输出函数调用的结果,您需要编写
printf
的调用,例如This declaration
declares a pointer to the array type
int[3]
.So there is declared a scalar object of a pointer type that you are trying to initialize using a brace enclosed list of initializers with more than one initializer of an incompatible pointer type.
Instead you need to write
The function designators used as initializers are implicitly converted to pointers to the functions.
So there is no need to write as for example
&a
though such an expression is also valid to be used as an initializer.To simplify the array declaration you could introduce a typeded name for the function pointer type.
For example
Now the array declaration can look the following way
And to output results of function calls you need to write calls of
printf
like