Infinite loop help

I am creating a linked list from the keyboard and when executing its giving me a endless loop and i'm not sure why, some help would be greatly appreciated.
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
#include<iostream>
#include <cstdlib> 

using namespace std;

struct list_el {
	int value;
	struct list_el * next;
};
typedef struct list_el item;

int main() {
	item * pre, * head;
	int num;
	head = NULL;
	cout << "Enter 5 Integers: " << endl;
	for(int index = 1;index <= 5; index++){
		cin >> num;
		pre = (item *)malloc(sizeof(item));
		pre -> value = num;
		pre -> next = head;
		head = pre;
	}
	pre = head;
//printing values
	while(pre){
		if(pre -> next == NULL)
			cout << pre -> value << " ";
		else{
			pre = pre -> next ;
			cout << pre -> value << " ";
		}
	}
}
Wow, please use functions as well as "new" and "delete" keywords. Your program will leak memory now, since you don't free() it (and we don't really use malloc in C++).

As for why you've got endless loop, the answer is simple: while(pre)... loop never updates pre. Go along the if and see your mistake.
Oh i see, the book my class is using is written in C but i prefer C++, so I was following the guidelines from that. I will check out the "new" and "delete" keywords. And i see why now its giving me a endless loop now. Thanks for the help
Topic archived. No new replies allowed.