The problem is that inside this loop
for (int i = 2; i < 5; i++){
Class next;
next.key = 2;
p->next = &next;
p = p->next;
}
for each its iteration you are using the same local variable. Thus for the second iteration of the loop p->next
points to the same local object.
So your porgram has undefined behaviour because this local object is not alive after exiting the loop. In general case the memory occupied by the local variable can be overwritten.
It seems that as result you have to nodes. One is c
that points to already "died" node next and the died node next
that points to itself and keeps the last value that was stored in data member key
that is 4.
You should either dynamically allocate each node or use an array of nodes of the list.
Here is a demonstrative program that shows how you could use a simialr approach by means of an array.
#include <iostream>
struct Class
{
public:
int key;
Class *next;
};
int main()
{
const size_t N = 4;
Class c[N];
c[0].key = 1;
Class *p = &c[0];
for ( size_t i = 1; i < N; i++ )
{
c[i].key = i + 1;
p->next = &c[i];
p = p->next;
}
p = &c[0];
for ( int i = 0; i < N; i++ )
{
std::cout << p->key;
p = p->next;
}
std::cout << std::endl;
return 0;
}
The output is
1234