Mistu4u
Mistu4u

Reputation: 5416

Why can't I display the correct list values?

To check a sample list imlpementation I tried the following code. But whenever i am trying to display the result it is getting inside a loop. I cant find where is it getting wrong.

#include<stdio.h>
#include<stdlib.h>

typedef struct linkedlist
{
    int data;
    struct linkedlist *next;
}node;

int main()
{
    int ch,num;

    node *head=NULL;
    head=(node *)malloc(sizeof(node));
    node *new=NULL;
    new=(node *)malloc(sizeof(node));
    node *temp=NULL;
    temp=(node *)malloc(sizeof(node));
    printf("\n1.Insert to list");
    printf("\n3.Display the list");
    printf("\n Enter Choice->");
    scanf("%d",&ch);
    switch(ch)
    {
     case 1:printf("\n Enter data->");
            scanf("%d",&num);
            new->data=num;
            new->next=NULL;
            head->next=new;
            break;

     case 3: temp=head;
            while(temp!=NULL)
            {
                printf("\n %d",temp->data);
                temp=temp->next;
            }


                break;
     default:printf("Wrong Choice");
              break;

    }
    return 0;
 }

Upvotes: 0

Views: 104

Answers (3)

Max E.
Max E.

Reputation: 1917

There are two mistakes here.

  1. You are only allocating "new" once. This means you are reusing the same node every time the user enters "1" and actually linking it to itself.
  2. You shouldn't be allocating a node for "temp" at all, since you are not using it. You are actually loosing the pointer to that allocated node with this line: case 3: temp=head; This is called a "memory leak."

I suggest that you study pointers a bit more; they seem to be confusing you.

Upvotes: 1

David Gish
David Gish

Reputation: 750

Why do I feel like this is a homework question?

Here are some hints:

  1. head is allocated, but never initialized and this is where you start printing from. Frankly, I'm surprised it doesn't crash.

  2. Your menu allows you to print the list OR enter a number, after which the program ends. I suspect you are entering a number, then running the program again to print out the list. The program state isn't preserved between runs.

Upvotes: 1

codaddict
codaddict

Reputation: 454960

I can see the following problems:

1) You are not looping with the options as a result user can do just one thing (either insert or display) in each run of your program. If he chooses to insert he can't display and if he chooses to display there isn't any list to display.

2) You need to create a new node every time you want to insert a new node in the list. Currently you are just changing the data of the same node (pointed to by new).

Upvotes: 0

Related Questions