4

I am new to linked list, now I have little problems in population of nodes.

Here I could populate first node of linked list but the gets() function doesn't seems to pause the execution to fill the next node.

Output is like:

Var name : var
Do you want to continue ?y
Var name : Do you want to continue ?  // Here I cannot input second data

Here is my code:

struct data
{
    char name[50];
    struct data* next;
};
struct data* head=NULL;
struct data* current=NULL;
void CreateConfig()
{
    head = malloc(sizeof(struct data));
    head->next=NULL;
    current = head;
    char ch;
    while(1)
    {
        printf("Var name : ");
        gets(current->name);    //Here is the problem,
        printf("Do you want to continue ?");
        ch=getchar();
        if(ch=='n')
        {
            current->next=NULL;
            break;
        }
        current->next= malloc(sizeof(struct data));
        current=current->next;
    }
}
codaddict
  • 445,704
  • 82
  • 492
  • 529
Bijoy
  • 399
  • 2
  • 7
  • 15
  • maybe you need to do type cast, add `(data *)` before every `malloc`, like this `(data *) malloc(sizeof(struct data))` – behzad.nouri Nov 21 '11 at 18:38
  • @runnerup: That is a bad idea: http://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc – ChrisWue Nov 21 '11 at 18:42
  • What is the problem you are seeing exactly? Does the program crash or something else? – ChrisWue Nov 21 '11 at 18:45
  • function "malloc" returns a void pointer, you should manually convert it to (data*) type – zebrilo Nov 21 '11 at 18:45

3 Answers3

7

This happens because:

ch=getchar();

read either y or n from the input and assigns to ch but there a newline in the input buffer which gets read by the gets in the next iteration.

To fix that you need to consume the newline following the y/n the user enters. To do that you can add another call to getchar() as:

ch=getchar(); // read user input
getchar();    // consume newline

Also the function fgets should be used in place of gets. Why?

Community
  • 1
  • 1
codaddict
  • 445,704
  • 82
  • 492
  • 529
2

It's exactly what @codaddict said. You need to clean the buffer.

void fflushstdin( void )
{
    int c;
    while( (c = fgetc( stdin )) != EOF && c != '\n' );
}

You can read this links that explains it very well:

  1. c-faq
  2. And this mdsn if you are on windows.

One more thing, try to always use fgets -instead of gets-, as it is impossible to prevent buffer overflows if you are using gets.

You could read the section "Use of safe libraries" at this link

Cacho Santa
  • 6,846
  • 6
  • 41
  • 73
0

you should also add a line like

 current->next = 0;

after

 current=current->next;

to ensure that the last element's next is not dangling.

Walter
  • 44,150
  • 20
  • 113
  • 196