函数指针结构数组 C
Array of structures of function pointers C
我正在尝试初始化包含函数指针的结构数组:
typedef struct struct_actioncommand {
char *action;
void (*command)(my_type);
} type_actioncommand;
为了用函数名初始化每个指针,我使用了这个方法:
static const type_actioncommand g_cmd_tab[] = {
{"Action1", function1},
{"Action2", function2},
{"Action3", function3},
{NULL, NULL}
};
但是没用。
当我尝试使用 "gcc" 进行编译时,出现以下消息:
myfile.c:16:3: error: initialization from incompatible pointer type [-Werror]
{"Action1", function1},
^
myfile.c:16:3: error: (near initialization for g_cmd_tab[0].command) [-Werror]
myfile.c:17:3: error: initialization from incompatible pointer type [-Werror]
{"Action2", function2},
^
myfile.c:17:3: error: (near initialization for g_cmd_tab[1].command) [-Werror]
myfile.c:18:3: error: initialization from incompatible pointer type [-Werror]
{"Action3", function3},
^
myfile.c:18:3: error: (near initialization for g_cmd_tab[2].command) [-Werror]
cc1: all warnings being treated as errors
每个函数都是根据这个原型定义的:
void function1(my_type *var1);
我现在有点困惑,因为我不知道如何解决我的问题。
有什么想法吗?
在您的结构中,command
成员:
void (*command)(my_type);
具有类型“指向函数的指针,该函数采用 my_type
和 returns void
.
类型的参数
你的函数:
void function1(my_type *var1);
具有类型“函数,该函数采用 my_type *
和 returns void
类型的参数。
函数指针的参数与您分配给它们的函数的参数不匹配。这使得指针不兼容。
要解决此问题,请更改函数指针的类型以匹配分配给它的函数:
void (*command)(my_type *);
我正在尝试初始化包含函数指针的结构数组:
typedef struct struct_actioncommand {
char *action;
void (*command)(my_type);
} type_actioncommand;
为了用函数名初始化每个指针,我使用了这个方法:
static const type_actioncommand g_cmd_tab[] = {
{"Action1", function1},
{"Action2", function2},
{"Action3", function3},
{NULL, NULL}
};
但是没用。 当我尝试使用 "gcc" 进行编译时,出现以下消息:
myfile.c:16:3: error: initialization from incompatible pointer type [-Werror]
{"Action1", function1},
^
myfile.c:16:3: error: (near initialization for g_cmd_tab[0].command) [-Werror]
myfile.c:17:3: error: initialization from incompatible pointer type [-Werror]
{"Action2", function2},
^
myfile.c:17:3: error: (near initialization for g_cmd_tab[1].command) [-Werror]
myfile.c:18:3: error: initialization from incompatible pointer type [-Werror]
{"Action3", function3},
^
myfile.c:18:3: error: (near initialization for g_cmd_tab[2].command) [-Werror]
cc1: all warnings being treated as errors
每个函数都是根据这个原型定义的:
void function1(my_type *var1);
我现在有点困惑,因为我不知道如何解决我的问题。 有什么想法吗?
在您的结构中,command
成员:
void (*command)(my_type);
具有类型“指向函数的指针,该函数采用 my_type
和 returns void
.
你的函数:
void function1(my_type *var1);
具有类型“函数,该函数采用 my_type *
和 returns void
类型的参数。
函数指针的参数与您分配给它们的函数的参数不匹配。这使得指针不兼容。
要解决此问题,请更改函数指针的类型以匹配分配给它的函数:
void (*command)(my_type *);