C 如何使结构常量中的函数指针用于初始化常量数组?

C 如何使结构常量中的函数指针用于初始化常量数组?,c,arrays,struct,initialization,constants,C,Arrays,Struct,Initialization,Constants,我有以下常量结构,它保存函数指针: /* module1.h */ typedef struct my_struct my_struct_t; struct my_struct { void (*funcPtr1)(void); void (*funcPtr2)(void); } extern const my_struct_t myStruct1; /* module1.c */ #include <module1.h> static void func

我有以下常量结构,它保存函数指针:

/* module1.h */

typedef struct my_struct my_struct_t;

struct my_struct
{
   void (*funcPtr1)(void);
   void (*funcPtr2)(void);
}

extern const my_struct_t myStruct1;



/* module1.c */

#include <module1.h>

static void func1(void)
{
   // do something
}

static void func2(void)
{
   // do something else
}

const my_struct_t myStruct1 = {
   .funcPtr1 = &func1,
   .funcPtr2 = &func2
}
/*模块1.h*/
类型定义结构我的结构我的结构;
结构我的结构
{
无效(*funcPtr1)(无效);
无效(*funcPtr2)(无效);
}
外部结构我的结构我的结构1;
/*模块1.c*/
#包括
静态void func1(void)
{
//做点什么
}
静态void func2(void)
{
//做点别的
}
const my_struct myStruct1={
.funcPtr1=&func1,
.funcPtr2=&func2
}
到目前为止还不错

现在,我想创建上述结构的常量数组,并从该结构的实例中分配函数指针:

/* module2.c */

#include <module1.h>

const my_struct_t arrayOfMyStruct[] = {
   { myStruct1.funcPtr1, myStruct1.funcPtr2 },
   // ...
}
/*module2.c*/
#包括
构造我的结构阵列系统结构[]={
{myStruct1.funcPtr1,myStruct1.funcPtr2},
// ...
}
编译器抛出一个错误,并说表达式
“myStruct1.funcPtr1”
“myStruct1.funcPtr2”
不是常量。

怎么了?

myStruct1
是用限定符const声明的,但它不是常量。静态初始化要求它为,并且
ArrayOfSystemStruct
具有静态存储持续时间

具有静态或线程存储持续时间的对象的初始值设定项中的所有表达式 应为常量表达式或字符串文字

您可以直接使用函数初始化它:
{func1,func2},

或者获取指针的地址:
{&myStruct1.funcPtr1,&myStruct1.funcPtr2},

在这种情况下,必须为数组使用不同的结构类型:

typedef struct 
{
   void (*const *funcPtr1)(void);
   void (*const *funcPtr2)(void);
} my_struct2_t;
调用函数的语法必须更改:

(*arrayOfMyStruct[0].funcPtr2)();

你确定包括在内吗。对于包含本地文件
#包含“module1.h”
。它肯定包含在内。这不是一个与函数指针有关的问题,而是一个与初始化变量有关的问题。@Jeyaram初始化是正确的。这是一个结构数组。第一个解决方案在我的应用程序中是不可能的。事实上,module2.c中的数组类型是另一种类型,但它包含相同的函数指针类型,所以我使用相同的类型来解释这个问题。第二种解决方案的意思是我必须更改module2.c的结构,使其处理“指向函数指针的指针”,对吗?但实际上我不想改变这一点。除了上面列出的方法之外,是否有任何方法可以使“myStruct1.funcPtr1”保持不变???@momjovi89。不