【问题标题】:list_entry() in list.h returning a warninglist.h 中的 list_entry() 返回警告
【发布时间】:2011-02-17 09:10:22
【问题描述】:

考虑这段代码:

 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 :这只是一个大代码的小sn-p。我很抱歉让它看起来像我试图在不存在时使用 Trade* 对象。在代码中,我确实使用了typedef来定义struct Trade;

【问题讨论】:

  • 如果不包括 list_entry 的定义,我们怎么知道这里发生了什么?大概它是一个宏,因为您将类型(交易)传递给它。附言我猜它应该是 Trade*,而不是 Trade,但我在没有定义的情况下在黑暗中拍摄。
  • list_entry() 函数定义在 LINUX KERNEL 的 list.h 中。List.h 是内核链表的标准头文件。如果您坚持,我可以附上代码

标签: c linux gcc linux-kernel gnu


【解决方案1】:

为此,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);
            }

        }

【讨论】:

  • 嗯,正是我害怕的事情。谢谢,是的,我也有同样的预感。
【解决方案2】:

DisplayTrades 函数中,将 Trade 结构的指针声明为其参数时,您必须使用

struct Trade * Tbook.

【讨论】:

  • @Algorithmist @Lundin 请看看我的编辑。我忘记将它添加到 sn-p,但是从它获取的较大代码库确实包含 struct Trade Trade; 的 typedef(现在已添加到 sn-p)
  • 或者更好的是,总是使用'​​struct trade'。这避免了 typedef 引起的命名空间污染。
  • @Lundin 结构类型定义在 Linux 内核代码中不受欢迎。对于任何打算在上游共享代码的人来说,这将是一个糟糕的建议。
  • @user611775 没有所谓的“命名空间污染”。专业程序员在其编码标准中有变量/函数/类型命名,并使用命名前缀。
  • @Eric 除了宗教信仰之外还有什么特别的原因吗?
猜你喜欢
  • 2014-12-05
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
相关资源
最近更新 更多