【发布时间】: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).head 是 struct cell_s 所以我应该能够访问属性 next 吗?但是编译器不让我这样做。
谢谢。
【问题讨论】:
-
通过将
(*list).head = (*list).head.next替换为(*list).head = (*tmp).next解决 -
除了构建错误(很简单,
(*list).head(或list->head)的类型是什么?)在取消引用潜在的未初始化或空指针时,您还可能有一些未定义的行为。跨度>