加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么在初始化一个函数指针数组时有一个“警告”?

发布时间:2020-12-16 03:24:01 所属栏目:百科 来源:网络整理
导读:我尝试初始化一个数组的函数指针,我有“警告”: ring-buffer.c:57:19: warning: assignment from incompatible pointer type [enabled by default]RBufP-rbfunc[0] = RBufPush; ^ 但邻里的确定: /*typedef for func pointer*/typedef RBRetCod_t (*RBFunc)
我尝试初始化一个数组的函数指针,我有“警告”:
ring-buffer.c:57:19: warning: assignment from incompatible pointer type [enabled by default]
RBufP->rbfunc[0] = &RBufPush;
                 ^

但邻里的确定:

/*typedef for func pointer*/
typedef RBRetCod_t (*RBFunc)();

/*RBufP*/
typedef struct {
    RBufSiz_t size; /*size and mask*/
    RBufDat_t rbufdat;
    RBufPoint_t head,tail;
    RBFunc rbfunc[3]; /*announce of function pointers array*/
} RBuf_t;
RBuf_t *RBufP;
...

/*init for func pointers array*/
RBufP->rbfunc[2] = &RBufDel; /*it is ok*/
RBufP->rbfunc[1] = &RBufPull; /*it is ok*/
RBufP->rbfunc[0] = &RBufPush; /*it is bad,why???*/

...

/*body of the functions*/
RBRetCod_t RBufPull(unsigned char *dat)
{
        return RBSUCC;
}
RBRetCod_t RBufDel(void)
{
        return RBSUCC;
}
RBRetCod_t RBufPush(unsigned char dat)
{
        return RBSUCC;
}

请告诉我为什么在这一行发生警告:RBufP-> rbfunc [0] =& RBufPush,但在相邻的行不存在?

解决方法

请参见C11节6.7.6.3§14,指定何时将两种功能类型视为兼容性:

[…] If one type has a parameter type list and the other type is specified by a function declarator that is not part of a function definition and that contains an empty identifier list,the parameter list shall not have an ellipsis terminator and the type of each parameter shall be compatible with the type that results from the application of the default argument promotions. […]

这是RBufPull和RBufDel的情况,但不会将RBufPush作为unsigned char提升为int.

如果您通过RBFunc类型的指针调用RBuPush,则int参数将被推送到堆栈,而RBufPush将期望一个unsigned char.根据呼叫约定和字节顺序,您将得到不正确的结果.

一个解决方案是更改RBufPush以获取一个int参数.另一个是使用一个演员,即

RBufP->rbfunc[0] = (RBFunc)&RBufPush;

在调用rbfunc [0]之前,需要将其转换为正确的类型RBRetCod_t(*)(unsigned char).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读