【问题标题】:Expression must have struct or union type表达式必须具有结构或联合类型
【发布时间】:2018-03-27 18:47:25
【问题描述】:

我正在尝试在 C 中使用堆栈/链表实现。我在堆栈的pop 函数上苦苦挣扎。

这是我的堆栈/链表实现的样子:

// a cell
struct cell_s
{
  void *elem;
  struct cell_s *next;
};
typedef struct cell_s cell_t;

// the list is a pointer to the first cell
struct linkedlist_s
{
  struct cell_s *head;
  int len;
};
typedef struct linkedlist_s linkedlist_t;

这是弹出功能:

/**
 * Pop remove and return the head
 */
cell_t *pop(linkedlist_t *list)
{
    if ((*list).len == 0) {
        // we cannot pop an empty list
        return NULL;
    }
    else 
    {
        cell_t* tmp = (*list).head;
        (*list).head = (*list).head.next; // <-- error occurs here
        (*tmp).next = NULL;
        return tmp;
    }
}

我不明白我做错了什么。 (*list).headstruct cell_s 所以我应该能够访问属性 next 吗?但是编译器不让我这样做。

谢谢。

【问题讨论】:

  • 通过将(*list).head = (*list).head.next替换为(*list).head = (*tmp).next解决
  • 除了构建错误(很简单,(*list).head(或list-&gt;head)的类型是什么?)在取消引用潜在的未初始化或空指针时,您还可能有一些未定义的行为。跨度>

标签: c pointers struct


【解决方案1】:

head 字段不是struct cell_s。它是一个struct cell_s *,即指向struct cell_s 的指针。因此,您需要使用-&gt; 运算符来取消引用并访问该成员。

list->head = list->head->next;

还要注意ptr-&gt;field(*ptr).field 更容易阅读。

【讨论】:

  • 谢谢,我不知道 -&gt; 是 C 语言中的东西
  • @truvaking 很高兴我能帮上忙。如果您觉得有用,请随时 accept this answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多