2017-01-02 125 views
0

我正在处理链表和指针。这是一个包含推送功能的简单代码。在推送我的元素并尝试打印第一个成员之后,执行的代码在运行时崩溃。但是,当将相同的指针传递给print_list函数并将其应用于print_list函数时,它可以正常工作。但是,当直接在主函数中使用它并应用printf函数时,它会崩溃。C编程错误,打印链表,在运行时执行代码崩溃

#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; 
} 
} 
+2

'list'是'**',但是你用'&'传递它,所以“receiver”实际上变成了'***' - 作为一个三星程序员不是一件好事;-) – John3136

回答

1

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

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 
    } 
} 

使用iterator而不是:

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;

并在此之后改变了你不需要任取头的地址,把它传递给print_list:

print_list(&ptr) - >print_list(ptr)

或间接引用它在printf中:

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