我一直在研究自指的结构,尤其是链接到C分配。问题是,当我尝试将指针推迟到列表的头部时,我会得到segfault或"来自不兼容指针类型的分配"。
我研究了有关操纵链接列表的解释,并试图遵循他们的示例来消除头部,但是当我这样做时,我一直在得到segfault。我还使用在线gdb进行调试,segfaults来自:
new_node->next = (*h);
(*h) = new_node;
crawler = (*head_of_list);
因此,我试图避免退出引用,它停止了Segfault,但仍然无法使用。它认为将列表的头部脱颖而出就是在这里有些困惑。
#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("%dn", 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;
}
关于如何解决这一值得赞赏的任何帮助。
您将头指针定义为0:
h0 = null;
然后您在此处将其解释:
new_node-> next =(*h(;
指针指向地址为零,您将获得一个segfault。确保它指向有效内存:(