C编程错误,打印链表,在运行时执行代码崩溃

我正在研究链表和指针。 这是一个包含推送function的简单代码。 在推送我的元素并尝试打印第一个成员后,执行的代码在运行时崩溃。 但是,当将相同的指针传递给print_list函数并在print_list中应用printf函数时,它可以正常工作。 但是当在main函数中直接使用它并应用printf函数时,它会崩溃。

#include #include typedef struct list{ int order; struct list *next; }list; void push(struct list **arg,int i); int main() { struct list **ptr=NULL; for(int i=0;iorder); //Here run time error return 0; } void push(struct list **arg,int i){ struct list *temp; temp= malloc(sizeof(list)); temp->order=i; temp->next=*arg; *arg=temp; } void print_list(list ** head) { while ((*head) != NULL) { printf("%d\n", (*head)->order); //Here works fine too ! *head = (*head)->next; } } 

这段代码中有几个指针管理错误。

 void print_list(list ** head) { while ((*head) != NULL) { printf("%d\n", (*head)->order); *head = (*head)->next; // print_list is clearly a readonly function, you don't want to modify head of the list } } 

改为使用迭代器:

 void print_list(list *head) { // Passing a copy of head pointer here, so real head can't be changed. struct list *iter = head; while (iter != NULL) { printf("%d\n", iter->order); iter = iter->next; } } 

struct list **ptr=NULL; – 你想在这里声明指向列表头部的指针,但是你正在声明指向这个指针的指针。

将其更改为: struct list *ptr = NULL;

在此更改之后,您无需使用head的地址将其传递给print_list:

print_list(&ptr) – > print_list(ptr)

或者在printf中取消引用它:

printf("%d\n", (*ptr)->order) – > printf("%d\n", ptr->order)