c - C中main方法中链表遍历中的段错误

标签 c linked-list

获取段 zsh:从 main 方法遍历链表时出现段错误(核心已转储)。但是在调用 printList 方法时工作正常。想得到一些直观的解释以及如何从 main 方法让它工作。

#include <stdio.h>
#include <string.h>
struct Node{
   int data;
   struct Node *next;
};

void printList(struct Node *head){
   struct Node *cursor= head;
   while(cursor !=NULL){
     struct Node currentNode = *cursor;
     printf("%d -->",currentNode.data);    
     cursor=currentNode.next;
   }
}

int main(){
   struct Node *head;     
   struct Node node1;
   node1.data=11;
   struct Node node2;
   node2.data=12;
   struct Node node3;
   node3.data=13;
   struct Node node4;
   node4.data=14;   

  // printf("Node 1 %d ",node1.data);
  // printf("Node 2 %d ",node2.data);
  // printf("Node 3 %d ",node3.data);

   head = &node1;
   node1.next=&node2;
   node2.next=&node3;
   node3.next=&node4;
  // printf("Node 1 %d ",node1.data);
  // printf("Node 2 %d ",node2.data);
  // printf("Node 3 %d ",node3.data);   
  // printList(head); 
struct Node *cursor= head;
   while(cursor !=NULL){
       struct Node currentNode = *cursor;
       printf("%d -->",currentNode.data);
       cursor=currentNode.next;
    }


   return 0;
}

最佳答案

使node4.next=NULL结束遍历。这就是您面临问题的原因。

否则您的 cursor!=NULL 检查条件将永远不会终止。因为它包含一些垃圾值。 (如果你不初始化)

  • 同样对于 100 个节点,你会把整个创建过程写 100 次吗?

您应该创建一个方法来将节点添加到列表的头部。那将是理想的。

另请阅读一些有关动态内存分配的内容。为了给你一个插入,我提供了一些想法。阅读它,查看手册。

例如,如果你想动态分配一个节点。你可以这样做:-

struct node *tempNode;
tempNode = malloc(sizeof(struct node));
if(tempNode == NULL){
    fprintf(stderr,"%s","Error in malloc");
    exit(1);
}
..
...

无论您使用 malloc 分配什么,都在逻辑结束时释放它。

有点像,

free(tempNode);
tempNode=NULL;

回答您的评论:- 不要依赖未定义的行为。取消引用垃圾值会调用未定义的行为。您必须避免它以使您的程序行为稳定。


注意事项

 struct Node currentNode = *cursor;
 printf("%d -->",currentNode.data);    

可以在一行中轻松完成

 printf("%d -->",cursor->data); //Also (*cursor).data

关于c - C中main方法中链表遍历中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47012950/

相关文章:

c - 需要帮助使用 C 语言通过 GTK 创建 TicTacToe

c - Ref/DeRef 双点链接列表

c - 将链表数组传递给函数

c - 从文件读取后打印链表的段错误

将 C 和汇编编译为纯机器代码?

c - 新手使用 malloc 处理 char

c - 为什么我不能在函数外分配(由 malloc 动态分配)变量?

c++ - 在一个范围内生成不同的随机数

java - LinkedList subList 返回 List 而不是 LinkedList?

java - 如何正确更新链表