C语言栈/链表实现中Pop函数报错“Expression must have struct or union type”求助
Hey there, let's work through this pop function issue step by step! That error message is telling you that you're trying to access a struct member the wrong way—usually mixing up the . and -> operators when dealing with pointers.
First, Let's Recap Your Struct Definitions
Here's the code you shared, formatted for clarity:
// 单元格结构体 struct cell_s { void *elem; struct cell_s *next; }; typedef struct cell_s cell_t; // 链表指向首个单元格 struct linkedlist_s { struct cell_s *head; int len; }; typedef struct linkedlist_s linkedlist_t;
The Root Cause of the Error
Your pop function takes a linkedlist_t *lis pointer as an argument. When accessing members of a struct pointer, you need to use the -> operator instead of .. If you wrote something like lis.head in your code, the compiler throws that error because . only works on actual struct/union instances, not pointers to them.
Correct Pop Function Implementation
Here's a fixed, complete version of the pop function that handles edge cases and uses the right member access syntax:
/** * Pop remove and return the head */ cell_t *pop(linkedlist_t *lis) { // Handle edge cases: null list pointer or empty stack if (lis == NULL || lis->len == 0) { return NULL; } // Grab the current head cell cell_t *popped_cell = lis->head; // Move the list's head to the next cell lis->head = popped_cell->next; // Decrement the stack length lis->len--; // Optional: Disconnect the popped cell from the stack to prevent accidental access popped_cell->next = NULL; return popped_cell; }
Key Fixes Explained
- Replaced any
lis.headwithlis->head(sincelisis a pointer) - Added checks for
NULLinput and empty stacks to avoid crashes - Disconnected the popped cell's
nextpointer to prevent unintended side effects later
内容的提问来源于stack exchange,提问作者truvaking

