c - Inserting a node at the end of a doubly linked list -
i tried inserting node @ end of doubly-linked list insert function process execution stops abruptly after sec insertion. tried checking out address of pointer variable used in insert function , show code works fine until 3rd insert function. how can prepare code?
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node* next; struct node* prev; }; void insert(struct node** header,int data) { struct node* newnode=(struct node*)malloc(sizeof(struct node*)); newnode->data=data; newnode->prev=null; newnode->next=null; if(*header == null) { *header=newnode; return; } struct node* temp = *header; while(temp->next != null) { temp=temp->next; } temp->next = newnode; newnode->prev = temp; printf("%d\n**\n", temp->next); } void main() { struct node* head = null; insert(&head, 4); insert(&head, 45); printf("\n main head %d", head); insert(&head, 8); printf("testing"); insert(&head, 69); }
you not allocating plenty memory
struct node* newnode=(struct node*)malloc(sizeof(struct node*)); // here allocate 4 bytes (or 8 bytes on 64 bit system)
should be:
struct node* newnode = (struct node*)malloc(sizeof(struct node));
then works fine.
c data-structures doubly-linked-list
No comments:
Post a Comment