0

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

2
  • For one thing, it looks like display is not showing the last element of the list. For instance, if the list has exactly one element, the while loop will exit immediately before doing anything. Commented Oct 17, 2017 at 18:56
  • And printf("%d\t",&pointer->data); --> printf("%d\t", pointer->data); Commented Oct 17, 2017 at 20:55

1 Answer 1

2

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");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.