c - 在 C 中操作链表时如何解决这个段错误问题?

标签 c pointers linked-list segmentation-fault self-reference

我一直在研究自引用结构和链表,特别是用于 C 作业。问题是,当我尝试取消引用指向列表头部的指针时,我得到了段错误或“来自不兼容指针类型的分配”。

我看过this explanation关于操作链接列表并尝试按照他们的示例取消引用头部,但是当我这样做时我总是遇到段错误。 我也用过onlinegdb调试过,段错误来自:

new_node->next = (*h);
(*h) = new_node;
crawler = (*head_of_list);

所以我试图避免取消引用,它停止了段错误但仍然无法正常工作。它认为取消引用列表的头部就是这一切的全部内容,所以这里有点困惑。

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


/*DATA STRUCTURES*/

typedef struct Node_s* Ptr_Node; /*Ptr_Node = pointer to struct node_s*/

typedef struct Node_s{
  int data;
  Ptr_Node next;
} Node_t;

typedef Ptr_Node* Head; /*a head = pointer to pointer of node*/

/*FUNCTIONS*/

/*Adds integer x in first position of the linked list*/
Head add_to_beginning(Head head_of_list, int x){
  Head h;
  h = head_of_list;
  Ptr_Node new_node;
  new_node = (Ptr_Node) malloc(sizeof(Node_t)); /*casting pointer type*/
  new_node->data = x;
  new_node->next = (*h); /*de-ref head to obtain pointer to first node*/
  (*h) = new_node; /*de-ref head to change what it points to*/
  return h;
}


void print_list(Head head_of_list){
  Ptr_Node crawler;
  crawler = (*head_of_list); /*points to first cell of list*/
  while(crawler != NULL){
    printf("%d\n", crawler->data );
    crawler = crawler->next;
  }
}

/*driver for testing*/
int main(void){
  Head h0, h1, h2;
  h0 = NULL;
  h1 = add_to_beginning(h0, 0);
  h2 = add_to_beginning(h1, 1);
  h3 = add_to_beginning(h2, 2);

  print_list(head_of_list);

  return 0;
}

非常感谢任何有关如何解决此问题的帮助。

最佳答案

您将 Head 指针定义为 0:

h0 = NULL;

然后你在这里取消引用它:

new_node->next = (*h);

指针指向地址零,你会得到一个段错误。确保它指向有效内存:)

关于c - 在 C 中操作链表时如何解决这个段错误问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55934117/

相关文章:

c - 指针需要比理论上更多的内存分配

c - 指针 C 的问题

c - 排序链表中的最高数字

c++ - 本地对象指针

在 C 中从 char * 转换为 char[31]

Java,类的多个实例重置为最新创建的实例

c到计算机组织和体系结构中的mips代码

c++ - 如何从文本文件加载链表?

c - 通过将指针设置为 NULL 来初始化 C 中的堆栈

c - 如何在 64 位应用程序中使用 32 位指针?