Reputation: 383
My doubly Linked list in C is displaying garbage value instead of value that I have entered, I have run this code on Turbo C++. the code compiled correctly with 0 errors and 0 warnings, but still it is displaying some garbage values. I have included the libraries (stdio.h,conio.h,stdlib.h,malloc.h) here is the code :
struct dlist
{
int data;
struct dlist *next;
struct dlist *prev;
};
struct dlist *head, *end;
void create_dlist()
{
char k='y';
struct dlist *new_node;
while(k=='y'||k=='Y') {
if(head==NULL) {
new_node=(struct dlist *)malloc(sizeof(struct dlist));
printf("Enter the integer value -> ");
new_node->data=0;
new_node->next=NULL;
new_node->prev=NULL;
scanf("%d",&new_node->data);
head=new_node;
end=new_node;
} else {
new_node=(struct dlist *)malloc(sizeof(struct dlist));
printf("Enter the integer value -> ");
new_node->data=0;
new_node->next=NULL;
new_node->prev=end;
scanf("%d",&new_node->data);
end->next=new_node;
end=new_node;
}
printf("Do you want to continue (y/n) ; ");
scanf(" %c",&k);
}
}
void display()
{
struct dlist *pointer;
pointer=head;
if(pointer!=NULL) {
while(pointer->next!=NULL) {
printf("%d\t",&pointer->data);
pointer=pointer->next;
}
} else {
printf("list is empty");
}
}
int main()
{
clrscr();
head=NULL;
end=NULL;
create_dlist();
display();
getch();
return 0;
}
A coded solution will be a great help
Upvotes: 0
Views: 1171
Reputation: 77
Whole problem is in display()
. First you print address and not value of data. Also, you are not printing last element. I made some changes. Ask me if you need any explanations.
void display()
{
struct dlist *pointer;
pointer=head;
if(pointer!=NULL)
{
while(pointer!=NULL)
{
printf("%d\t",pointer->data);
pointer=pointer->next;
}
}
else
{
printf("list is empty");
}
}
Upvotes: 2