Linked list not printing properly

Hi all,

I have been trying to make a linked list, but it wont print out properly with cout.

The output of the program when compiled with code blocks is

10

The program fails to compile with Dev-c++

The output I expect is

1
2
3
4
5
6
7
8
9
10


I have tried debugging the program and the loop doesn't seem to run properly. The variable "i" seems to go to 10 without first going through the numbers 1-9.

The code is as follows

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <cstdlib>
#include <iostream>

using namespace std;

struct number
{
       int x;
       number* pnext;
};

number* addnumber (number* plist, int i)
{
        number* ptemp = new number;
        ptemp->x = i;
        ptemp->pnext = plist;
};

int main(int argc, char *argv[])
{
    int i;
    number* plist = NULL;
    for (i = 0; i < 10; i++);
    {
        plist = addnumber(plist, i);
        cout << (plist->x);
        cout << ("\n");
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}
closed account (3CXz8vqX)
Question. You said that the program fails to compile. Why?

Secondly, your file looks like it'll do just fine without <cstdlib>....with some minor alterations of course (like replacing EXIT_SUCCESS with...0
Last edited on
I would be surprised if it compiled on any compiler.

addnumber must return a value. It doesn't.
I was wrong when I said it wouldn't compile with Dev-C++. It would compile, but give an error when I ran it. This was fixed by making addnumber return ptemp.

I also removed the <cstlib> header file. Somehow now it magically works.

The updated code is below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

using namespace std;

struct number
{
       int x;
       number* pnext;
};

number* addnumber (number* plist, int i)
{
        number* ptemp = new number;
        ptemp->x = i;
        ptemp->pnext = plist;
        return ptemp;
};

int main(int argc, char *argv[])
{
    int i;
    number* plist = NULL;
    for (i = 0; i < 10; i++)
    {
        plist = addnumber(plist, i);
        cout << (plist->x);
    }
    while (1);
    {};
}


It outputs

0123456789


Thanks guys.
Last edited on
Topic archived. No new replies allowed.