【问题标题】:Linked Lists are turning my brain to mush. How should I be doing this?链接列表让我的大脑变得糊涂。我应该怎么做?
【发布时间】:2011-09-25 15:51:38
【问题描述】:

我正在尝试使用链表来积累我对 C 中指针的了解。所以,我写了一个小例子,但是当我编译它时,我遇到了一个错误,我似乎无法弄清楚:

In function 'append_node': 
error: request for member ‘next’ in something not a structure or union

通过引用访问(或传递)结构的正确方法是什么?

#include <stdio.h>
#include <stdlib.h>

struct node {
  int val;
  struct node *next;
};

static int append_node(int val, struct node **head) {
  struct node *new_node;

  new_node = (struct node *) malloc(sizeof(struct node));
  new_node->val  = val;
  new_node->next = NULL

  *(head)->next = new;

  return 0;
}

int main() {
  int i;
  struct node *head;
  struct node *curr;

  head = NULL;
  curr = (struct node *) malloc(sizeof(struct node));

  for(i = 1; i <= 10; i++) {
      append_node(i, &curr);
      head = curr;
  }

  curr = head;
  while(curr) {
      printf("%d\n", curr->val);
      curr = curr->next ;
  }

  return 0;
}

任何帮助都会很棒!

【问题讨论】:

  • 致到目前为止所有回复的人:1) 指向新节点的指针称为new_node 而不是new。 2)通过将新节点分配给(*head)-&gt;next,列表的其余部分将被剔除(并泄露):这个想法是让新节点成为新的头,这就是为什么函数的参数是 double 指向节点的指针

标签: c pointers linked-list pass-by-reference


【解决方案1】:

我可以假设你在这一行得到了错误吗?

  *(head)->next = new;

我认为你需要做一个微不足道的改变:

  (*head)->next = new;

由于head 是指向指针的指针,因此当您取消引用它时,您会得到一个指针。 -&gt;next 对该指针进行操作。

【讨论】:

    【解决方案2】:

    两个问题:

    结尾处缺少;

    new->next = NULL
    

    改变

    *(head)->next = new;
    

    (*head)->next = new;
    

    【讨论】:

      【解决方案3】:

      试试这个:

      (*head)->next = new_node;
      

      **head 转为*head,然后呼叫会员。

      【讨论】:

        猜你喜欢
        • 2014-11-20
        • 1970-01-01
        • 1970-01-01
        • 2018-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-03
        • 2014-07-06
        相关资源
        最近更新 更多