c - 表达式必须具有结构或 union 类型

标签 c pointers struct

我正在尝试用 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).head 是一个 struct cell_s 所以我应该能够访问属性 next ?但是编译器不允许我这样做。

谢谢。

最佳答案

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

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

另请注意,ptr->field(*ptr).field 更易于阅读。

关于c - 表达式必须具有结构或 union 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49520351/

相关文章:

c - 评估存储在变量中的字符串并分配给数组

c - FindWindow() 偶尔失败(尝试 IPC)

c - 错误 '->' 的类型参数无效(有 'tree' )

c++ - 什么是数组到指针的衰减?

C、表达式必须是可修改的左值(改变结构成员的值)

c - 如何将结构变量复制到 C 套接字程序中的缓冲区中?

c - 为什么在 C bool 宏中使用 #define TRUE (1==1) 而不是简单地定义为 1?

c - 如何修改已传递给 C 函数的指针?

ios - 为什么不是所有项目都附加到数组中?

c - 是否需要创建指向结构的指针数组?