C编程错误,打印链接列表,在运行时执行的代码崩溃 [英] C Programming Error , printing linked list, at run time executed code crashes
问题描述
我正在处理链表和指针.这是一个包含推送功能的简单代码.在推送完我的元素并尝试打印第一个成员之后,执行的代码在运行时崩溃.但是,当将相同的指针传递给 print_list 函数并在print_list内应用 printf 函数时,它可以正常工作.但是,当直接在main函数中使用它并应用printf函数时,它会崩溃.
I'm working on linked lists and pointers. Here is a simple code including a push function. After pushing my elements, and trying to print the first member, the executed code crashes at run time. However, when passing the same pointer to the print_list function and applying the printf function inside print_list it works fine. But when using it directly in the main function and applying the printf function it crashes.
#include<stdio.h>
#include<stdlib.h>
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;i<10;++i){
push(&ptr,i);
}
print_list(&ptr); // Here works fine
printf("%d\n", (*ptr)->order); //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;
}
}
推荐答案
这段代码中存在一些指针管理错误.
There are a couple pointer management errors in this piece of code.
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;
- Your want to declare pointer to head of the list here, but you are declaring pointer to this pointer.
将其更改为:struct list *ptr = NULL;
此更改之后,您无需输入头像地址即可将其传递给print_list:
And after this changes you don't need to either take an address of head to pass it to print_list:
print_list(&ptr)
-> print_list(ptr)
或在printf中取消引用:
or dereference it in printf:
printf("%d\n", (*ptr)->order)
-> printf("%d\n", ptr->order)
这篇关于C编程错误,打印链接列表,在运行时执行的代码崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!