c - What is wrong with my code?It is crashing everytime i run it -
i tried write code implement , print linked list using loop.but code giving runtime error. crashing when run it.
#include <stdio.h> #include <stdlib.h> struct node { int info; struct node *next; struct node *prev; }var; int main() { struct node head; head.prev=null; struct node *temp; int i; for(i=1;i<5;i++) { struct node *new=malloc(sizeof(var)); temp->info=i; temp->next=new; new->prev=temp; temp=new; } for(i=1;i<=5;i++) { printf("%d ",temp->info); } return 0; }
first have initializehead.next
as head.prev
:
head.info = 0; head.prev=null; head.next=null;
you have initializeyour pointer temp
too. pointer should refer head @ start:
struct node *temp = &head;
adapt loop this:
for( int i=1;i<5;i++) { temp->next = malloc(sizeof(var)); // allocat new nod right on target temp->next->info=i; // set data on new node temp->next->prev = temp; // predecessor of successor temp temp = temp->next; // 1 step forward temp->next = null; // successor of last node null }
to print list of nodes use while
loop, start head step forward end:
temp = &head; while( temp != null ) { printf("%d ",temp->info); temp = temp->next; // 1 step forward }
Comments
Post a Comment