Hi, I'm having a strange problem with my linked list program.
This is slightly embarrassing because I'm getting back to coding in C++ after 4 years and don't remember much.

This is the code

#include<iostream.h>
#include<conio.h>
#include<string.h>


void printList(struct node *&);

struct node
{
node* next;
int data;
};

int main()
{
clrscr();

node *node1, *node2, *node3, *node4;
node1->data = 1;
node2->data = 2;
node3->data = 3;
node4->data = 4;

node1->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node1;

printList(node1);

getch();
return 0;
}

void printList(node*& head)
{
node* current = head;
int counter = 0;
while(current != NULL && counter < 10)
{
cout<<"\n "<<current->data;
current = current->next;
counter++;
}
}

It doesn't seem to be accessing node4, could someone point me towards what's wrong? Thanks.

:D

okay, changed the code to

node *node1 = new node;

Thanks! Why did it print the first three nodes though? How did it allocate memory if I didn't allocate memory initially?

Since your pointers are located on the stack they got the values that happen to be there, which might be a valid memory address, or not. A function's stack frame, which is the memory that the compiler allocates for your local variables, is not cleared (set to 0) when a function returns or when a new stack frame is allocated (normally). This means that the stack may contain more than just random data since parts of previous stack frames might be reused.

This question has already been answered. Start a new discussion instead.