【问题标题】:Function pointers in C: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]C 中的函数指针:警告:来自不兼容指针类型的赋值 [-Wincompatible-pointer-types]
【发布时间】:2019-06-09 06:02:58
【问题描述】:

考虑以下私有函数声明:

static void ParseCore(SI_32 num_param,const t_config_param config_param[CONFIG_PARAM_BUFFER_SIZE]);
static void ParseGnss(SI_32 num_param,const t_config_param config_param[CONFIG_PARAM_BUFFER_SIZE]);
static void ParseEaf(SI_32 num_param,const t_config_param config_param[CONFIG_PARAM_BUFFER_SIZE]);
static void ParsePps(SI_32 num_param,const t_config_param config_param[CONFIG_PARAM_BUFFER_SIZE]);
static void ParseImu(SI_32 num_param,const t_config_param config_param[CONFIG_PARAM_BUFFER_SIZE]);

在同一个源文件中另一个函数的定义中,我初始化了以下指针:

void (*ParseConfigGeneric)(SI_32, t_config_param*) = NULL;

以下所有作业都会收到帖子标题中指示的警告:

ParseConfigGeneric = &ParseCore;
ParseConfigGeneric = &ParseGnss;
ParseConfigGeneric = &ParseEaf;
ParseConfigGeneric = &ParsePps;
ParseConfigGeneric = &ParseImu;

这里是 GCC 的输出:

../src/core/time_mgmt.c: In function ‘ParseConfigFile’:
../src/core/time_mgmt.c:753:32: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
             ParseConfigGeneric = &ParseCore;
                                ^
../src/core/time_mgmt.c:757:32: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
             ParseConfigGeneric = &ParseGnss;
                                ^
../src/core/time_mgmt.c:761:32: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
             ParseConfigGeneric = &ParseEaf;
                                ^
../src/core/time_mgmt.c:765:32: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
             ParseConfigGeneric = &ParsePps;
                                ^
../src/core/time_mgmt.c:769:32: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
             ParseConfigGeneric = &ParseImu;

不过,代码确实可以编译并且似乎可以正常工作。我查找了类似的问题,但问题总是指针类型与原始函数的不同,但在这种情况下它们都是void* 并且参数匹配,所以我不知道问题是什么。

调用如下(编译器没有抱怨,我检查了每次都调用了正确的函数):

(*ParseConfigGeneric)(num_param, config_param);

【问题讨论】:

  • 我添加了 GCC 的输出。另外,我添加了缺少的“const”并解决了。我被 GCC 指向赋值而不是参数本身,就像我忘记 const 时通常所做的那样,我被抛弃了,但我想这是另一种情况。谢谢!您能否将您的消息发布为答案,以便我进行验证?

标签: c function pointers gcc


【解决方案1】:

函数和函数指针变量之间的第二个参数的类型不同。

在函数中它是一个指向const 的指针,它不在函数指针变量中。

类型需要完全相等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    相关资源
    最近更新 更多