gpt4 book ai didi

c - 为什么在初始化函数指针数组时有一个 "warning"?

转载 作者:太空狗 更新时间:2023-10-29 16:53:24 25 4
gpt4 key购买 nike

我尝试初始化一个函数指针数组,但出现“警告”:

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,指定何时应将 2 种函数类型视为兼容:

[...] 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. [...]

RBufPullRBufDel 是这种情况,但 RBufPush 不是这种情况,因为 unsigned char 被提升为 int

如果您通过 RBFunc 类型的指针调用 RBuPushint 参数将被压入堆栈,而 RBufPush 需要一个 unsigned char。根据调用约定和字节顺序,您会得到不正确的结果。

一个解决方案是将 RBufPush 更改为采用 int 参数。另一种是使用强制转换,即

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

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

关于c - 为什么在初始化函数指针数组时有一个 "warning"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30121976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com