【问题标题】:How do I access a structure member with a pointer in C?如何在 C 中使用指针访问结构成员?
【发布时间】:2021-01-29 07:29:57
【问题描述】:

我正在C 中练习链接列表。我的目标是我想使用 main 之外的函数删除一个节点。
我实现这个目标的计划是在不清除/删除/释放头指针的情况下访问下一个指针,但我得到一个错误:

“[错误] 请求成员 'nextptr' 不是结构或联合”

代码:

void del(struct node **head) {
    struct node *temp = *head;
    //this is what I believe is wrong, i need to access nextptr of head
    *head->nextptr = temp->nextptr->nextptr;
    free(temp->nextptr);
    temp->nextptr = NULL;

【问题讨论】:

  • 或许(*head)->nextptr?
  • 它修复了它,但为什么呢?
  • @DasFalscheGewinn 因为operator precedence。顺便说一句:temp->nextptr->nextptr; 看起来很可疑,如果 temp->nextptrNULL 你会遇到麻烦

标签: c data-structures linked-list


【解决方案1】:

-> 这样的后缀运算符的优先级高于一元*,因此*head->nextptr 被解析为*(head->nextptr) - 您正在尝试将-> 运算符应用于head(而不是*head) ,它是一个 指向一个指针 的指针,指向一个 struct 类型,因此是错误的。

要修复它,您需要在应用-> 运算符之前显式取消引用head,因此您需要将其写为(*head)->nextptr

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2018-03-06
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多