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');

}

It runs fine for me.

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

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.