0

Can anyone tell me why the following ligitimate code does not work, creating a linked list of characters from stdin?

struct Nodec {
       char element;
       Nodec *edge;
};


void Nodecin(Nodec *N) {

     char c;
     Nodec *tmp;

     if (N == NULL) {N = new Nodec;} 
     tmp = N;

    do {
      c = fgetc (stdin);
      tmp->element = c;
      tmp->edge = new Nodec;
      tmp = tmp->edge;
    } while (c != '\n');

}

Edited by mike_2000_17: Fixed formatting

4
Contributors
4
Replies
5
Views
11 Years
Discussion Span
Last Post by orko
0

By 'it runs' do you mean (a) you wrote a main to test it or (b) you simply tried to compile it?

0

First, what if stdin doesn't contain a newline character? You've got an infinite loop, then.

Second, your linked list is finishing off with a node whose tail pointer (and character) is uninitialized.

Third, if the value passed for N is null, then the caller cannot see the linked list you've created at all, so you've got a memory leak.

0

do {
c = fgetc (stdin);
tmp->element = c;
tmp->edge = new Nodec;
tmp = tmp->edge;
} while (c != '\n');

Here, the loop is running although the line is finished..... so better, if u use EOF or only while loop.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.