考虑这段代码:
struct Trade
{
float Price;
char* time;
int shares;
struct list_head *tradeList;
};
typedef struct Trade Trade;
void DisplayTrades(Trade* TBook)
{
if(TBook==NULL)
{
printf("NO TRADES\n");
return;
}
struct list_head *pos;
Trade *tmp;
pos = TBook->tradeList;
__list_for_each(pos,TBook->tradeList)
{
tmp = list_entry((pos),Trade,tradeList);
printf("Price %f, Time %s, Shares %d\n",tmp->Price,tmp->time,tmp->shares);
}
}
在这段代码中,当我编译时,编译器 gcc 在调用 list_entry 的行中返回一条警告,提示 initialization from incompatible pointer type
。
我在相同代码的其他地方使用了 list_entry,并且它的工作没有任何故障。所以唯一让我吃惊的是,也许我将意外的变量类型传递给函数,因此附加了结构 Trade 的定义。问题仍然存在。
如果知道哪里出了问题,将不胜感激。
EDIT :这只是一个大代码的一小段。我很抱歉让它看起来像我试图在不存在的情况下使用 Trade* 对象。在代码中,我确实使用了typedef来定义struct Trade;
最佳答案
为此,pos 必须是实际的列表头指针,但结构字段应该是 list_head 而不是 list_head 指针:
struct Trade
{
float Price;
char* time;
int shares;
struct list_head tradeList;
};
然后:
void DisplayTrades(Trade* TBook)
{
if(TBook==NULL)
{
printf("NO TRADES\n");
return;
}
struct list_head *pos;
Trade *tmp;
__list_for_each(pos,&TBook->tradeList)
{
tmp = list_entry((pos),Trade,tradeList);
printf("Price %f, Time %s, Shares %d\n",tmp->Price,tmp->time,tmp->shares);
}
}
关于c - list.h 中的 list_entry() 返回警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5026933/