C Programming Error , printing linked list, at run time executed code crashes

╄→尐↘猪︶ㄣ 提交于 2019-12-12 06:30:57

问题


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

回答1:


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

Use iterator instead:

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; - Your want to declare pointer to head of the list here, but you are declaring pointer to this pointer.

Change it to: struct list *ptr = NULL;

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)

or dereference it in printf:

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



来源:https://stackoverflow.com/questions/41434299/c-programming-error-printing-linked-list-at-run-time-executed-code-crashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!