【问题标题】:[C]: When a pointer to a pointer to a struct is passed in a function, why can't it change the elements of that struct? [duplicate][C]: When a pointer to a pointer to a struct is passed in a function, why can't it change the elements of that struct? [duplicate]
【发布时间】:2017-12-13 18:53:17
【问题描述】:
struct Node {
int data;
struct Node *next;
};

void insertAfterHead(struct Node **a, int x) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode -> data = x;
newNode -> next = *a -> next;
*a -> next = newNode;
}


int main() {
    struct Node *head = NULL;
    struct Node *second = NULL;
    struct Node *third = NULL;

    head = malloc(sizeof(struct Node));
    second = malloc(sizeof(struct Node));
    third = malloc(sizeof(struct Node));

    head -> data = 5;
    head -> next = second;

    second -> data = 10;
    second -> next = third;

    third -> data = 15;
    third -> next = NULL;

    insertAfterHead(&head, 10);

    return 0;
}

这是我在运行代码时收到的错误消息:

错误:成员引用基类型'struct Node *'不是结构或联合 新节点 -> 下一个 = *a -> 下一个;

错误:成员引用基类型'struct Node *'不是结构或联合 *a -> 下一个 = 新节点;

请尽可能描述,因为我是 C 初学者 :)

【问题讨论】:

  • 错误信息与代码不对应。并将其粘贴到此处,不是作为图像,而是作为文本。
  • 请将您的输出(错误消息)作为文本发布,并请发布您从您发布的代码(而不是其他代码)中获得的错误消息。
  • 在这种情况下,不需要传递指向指针的指针。
  • @EugeneSh。抱歉,我在询问时重命名了变量(为了澄清)。也添加了错误消息。
  • @JohnnyMopp - 是的,但我忘记了我想问这个问题的上下文,所以我编了:P

标签: c pointers struct linked-list


【解决方案1】:
*headRef->next

意思

*(headRef->next)

但你想要

(*headRef)->next

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 2022-12-02
    • 2022-12-01
    • 2018-01-20
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    相关资源
    最近更新 更多