You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言栈/链表实现中Pop函数报错“Expression must have struct or union type”求助

Fixing the "Expression must have struct or union type" Error in Your Stack's Pop Function

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.head with lis->head (since lis is a pointer)
  • Added checks for NULL input and empty stacks to avoid crashes
  • Disconnected the popped cell's next pointer to prevent unintended side effects later

内容的提问来源于stack exchange,提问作者truvaking

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:29:04