简体   繁体   English

为什么不能在C中初始化包含函数指针的结构数组?

[英]Why can't I initialize my array of structures containing function pointers in C?

my_functions.h my_functions.h

void * f1 (int * param);
void * f2 (int * param);
void * f3 (int * param);
void b1(int * param);
void b2(int * param);
void b3(int * param);

my_prog.c my_prog.c

#include <my_functions.h>

// Typedef my function pointers
typedef void * (*foo)(int*);
typedef void (*bar)(int*);

// Declare the structure that will contain function pointers
typedef struct _my_struct
{
    int tag;
    foo f;
    bar b;
}my_struct;

// Declare and initialize the array of my_struct
my_struct array[] =
{
    {1, f1, b1},
    {2, f2, b2},
    {3, f3, b3}
};

Compiler says: 编译器说:

warning: initialization from incompatible pointer type 警告:从不兼容的指针类型初始化

I looked at: 我看着:

But I still can't see what I missed... 但是我仍然看不到我错过的一切...
For me, all the types and the functions are known by the time I try to initialize my array. 对我来说,当我尝试初始化数组时,所有类型和函数都是已知的。
Can't the init be done outside a function ? 初始化不能在函数外部完成吗?

[EDIT] I am on Linux, using an embedded version for arm of GCC 4.9. [编辑]我在Linux上,对GCC 4.9使用嵌入式版本。

Ok so my code works just fine on my PC, it is actually the arm-gcc compiler that I use for my embedded target that throw this error because it seems it can't recognize the type of the function pointers without an explicit cast: 好的,这样我的代码就可以在我的PC上正常工作了,实际上是我用于嵌入式目标的arm-gcc编译器引发了此错误,因为如果没有显式的强制转换,它似乎无法识别函数指针的类型:

Here is the fix: 解决方法是:

my_struct array[] =
{
    {1, (foo)f1, (bar)b1},
    {2, (foo)f2, (bar)b2},
    {3, (foo)f3, (bar)b3}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM