【问题标题】:LinkedList in C errorC 中的 LinkedList 错误
【发布时间】:2017-08-22 17:19:49
【问题描述】:

我正在尝试用 C 编写一个 LinkedList。这是我的两个结构

struct node{
  int key;
  int value;
  struct node *next;
};

struct LinkedList {
  struct node *head;
};

这是我创建新节点的方法。

void createNode(int key, int value) {
  struct node *new_node;
  new_node->key = key;
  new_node->value = value;
  new_node->next = lList->head;
  lList->head = new_node;
}

我正在尝试使用下面的函数遍历 LinkedList。

void traverseNode(struct LinkedList *lList) {
  struct node current = *lList->head;
  while(current != NULL) {
    printf("%i", current->key);
    current = current->next;
  }
}

但是,我一直收到错误提示

invalid operands to binary expression ('struct node'
      and 'void *')

关于我的while 表达式。

另外,我收到一个错误

printf("%i", current->key);
current = current->next

错误是

成员引用类型'struct node'不是指针; 也许你打算使用 '.'

我很困惑,因为我认为在我的节点结构中,*next 被定义为一个指针,因此只能使用间接(->)语法来访问。

我是指针的初学者,因此感谢任何帮助。

【问题讨论】:

    标签: c pointers struct linked-list


    【解决方案1】:

    您不能将NULL 与非指针类型进行比较。

    将变量 current 声明为指针 + 删除 head 的取消引用,它将编译

    struct node * current = lList->head;
                ^          ^
    while(current != NULL)  // Now you can compare them
    

    您获得 SEGFAULT 是因为您取消引用未初始化的指针。在堆上分配足够的内存(动态存储持续时间)。

    struct node *new_node = malloc(sizeof(struct node));
    

    因为current 是指针

    printf("%i", current->key);
    current = current->next;
    

    现在应该可以了。

    【讨论】:

    • 当我这样做时,我得到以下错误,用不兼容类型'struct node'的表达式初始化'struct node *';删除 *
    • 所以,它编译但是当我运行它时,我得到一个segmentation fault: 11。这是因为我在void createNode 方法中创建新节点时没有使用malloc 分配内存吗?
    • 是的,这就是问题所在。
    • 即使在包含malloc 行之后,我仍然会收到 Seg Fault 错误。知道为什么吗?
    • Here(click) 是一个工作代码,你可以在那里启发:-)
    【解决方案2】:

    由于错误状态 current 是一个结构,而不是指针

    改成struct node *current = lList -> head;

    请记住,指针本身没有被引用对象的存储空间

    【讨论】:

      【解决方案3】:
      do{
      printf("%i", current->key);
      current = current->next;
      } while(current != NULL)
      

      这样做会通过查看下一个节点是否为空而不是整个结构来检查您是否在最后一个节点上

      【讨论】:

        【解决方案4】:
        void createNode(int key, int value) {
          struct node *new_node; // you need to malloc here
          new_node->key = key;
          new_node->value = value;
          new_node->next = lList->head;
          lList->head = new_node;
        }
        

        在访问指针之前必须进行 malloc。

        struct node *new_node = (struct node*)malloc(sizeof(struct node));
        

        也换个样子,

        struct node current = *lList->head;
        

        进入,

        struct node *current = *lList->head;
        

        【讨论】:

        • 它不会工作... :-) 看看底线,将struct node 分配给struct node*
        • 你指的是哪一行?
        猜你喜欢
        • 2015-08-05
        • 2017-10-14
        • 1970-01-01
        • 2020-11-02
        • 2012-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-01
        相关资源
        最近更新 更多