【问题标题】:Linked list C segmentation fault?链表C分段错误?
【发布时间】:2018-01-23 09:53:24
【问题描述】:

我试图在 C 中创建一个链表,但我遇到了分段错误? 我刚刚定义了结构,然后创建了一个简单的函数来创建单个节点并为其分配值,然后一个名为 append 的函数在列表末尾添加一个节点,主程序接受输入并追加列表,最后它打印列表。

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

typedef struct list {
  int value ;
  struct list *next ;
}node;

node* create(int value, node *next)
{
  //creating node and allocating memory
  node* new_node = (node*)malloc(sizeof(node));
  //assigning values to the node
  new_node->value = value ;
  new_node->next = next ;

  return new_node;
}
node* append(int value,node *head){
  //creating the node
  node* new_node = create(value,NULL);
  //handling the case in which the head is NULL, other words when we don't have a previous node to append to
  if (head == NULL) {
    head = new_node;
    return head;
  }
  //the standard procesdure
  else{
  //traversing the list
  node* cursor = head ;
  while (cursor != NULL) {
    cursor = cursor->next ;
  }
  // appending the node to the list
  cursor->next = new_node;
  return head;
}
}



int main(int argc, char const *argv[]) {
  int n ;
  printf("Enter the length of the list you wish to make\n");
  scanf("%d",&n );
  node* head = NULL;
  while (n--) {
    int value;
    printf("enter the value of the %d node\n",n);
    scanf("%d",&value);
    head = append(value,head);
  }
  //printing the list 
  node* cursor = head ;
  while (cursor !=NULL) {
    printf("%d\n",cursor->value );
    cursor = cursor->next;
  }
  return 0;
}

【问题讨论】:

    标签: c segmentation-fault


    【解决方案1】:
    while (cursor != NULL) {
        cursor = cursor->next ;
    }
    // appending the node to the list
    cursor->next = new_node;
    

    cursor 在您的 while 循环之后将为 NULL。而是这样做:

    while (cursor->next != NULL) {
        cursor = cursor->next ;
    }
    // appending the node to the list
    cursor->next = new_node;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 2011-03-14
      • 2013-10-21
      • 2012-06-12
      • 2015-12-28
      • 2020-09-10
      相关资源
      最近更新 更多