Trying to learn pointers.

Could someone tell me what is wrong with this code?

I'm just trying to re-teach myself the syntax but I can't get it down right.

I'm trying to create a list of numbers 1 thru 15 in order.

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
32
33
34
35
36
37
38
#include <iostream>

using namespace std;
    struct node{
        int number;
        node * next;
    };

node * list, * first;


int main()
{
    list = new node; first = new node;
    first -> number = 3000;
    first -> next = list;

    //first = list;

    for (int i = 1; i <= 15; ++i)
        {
            list -> number = i;
            list = list -> next;
        }

    list = first -> next; //*
    //list = first;

    for (int i = 1; i <= 15; ++i)
        {
            cout << "list -> number = " << list -> number << endl;
            list = list -> next;
        }

    cout << "End of Program. \n" << endl;
    return 0;
}
In the first loop you're assigning list->next (which is uninitialized) to list, so in the next iteration dereferencing list has undefined results.
Topic archived. No new replies allowed.