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

前端之家收集整理的这篇文章主要介绍了为什么在初始化一个函数指针数组时有一个“警告”?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试初始化一个数组的函数指针,我有“警告”:
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).

原文链接:/c/111574.html

猜你在找的C&C++相关文章