簡體   English   中英

在C中處理鏈接列表時,如何解決此段錯誤問題?

[英]How can I fix this segfault issue when manipulating linked-lists in C?

我一直在研究自引用結構和特別是C分配的鏈接列表。 問題是,當我嘗試取消對指向列表開頭的指針的引用時,會遇到段錯誤或“來自不兼容指針類型的賦值”。

我已經看過關於操縱鏈表的解釋 ,並試圖按照他們的例子來取消對頭部的引用,但是當我這樣做時,我一直會遇到段錯誤。 我還使用了onlinegdb進行調試,該段錯誤來自:

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

因此,我嘗試避免取消引用,它停止了segfaulting,但仍然無法正常工作。 它認為取消引用列表的開頭就是這里的全部含義,因此有點困惑。

#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);

指針指向地址零,您將遇到段錯誤。 確保它指向有效的內存:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM