Hello All, I'm having some problems printing a very simple linked list. The problem is with the end of the linked list, I'm getting
EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
and I can not figure out what is happening. Using the debugger I have concluded that the loop is not terminating at the last value and for some reason, it keeps looping.
I checked out this post and I was hoping it was the answer to my problem but it did not help.
http://www.cplusplus.com/forum/beginner/41713/
here is my code, it's simple, I'm just trying to get the feel of linked list.
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 39 40 41 42 43 44
|
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
int main()
{
node *n, *t, *h;
n = new node;
n->data = 1;
t = n;
h = n;
n = new node;
n->data = 2;
t->next = n;
t = n;
n = new node;
n->data = 3;
t->next = n;
t = n;
n = new node;
n->data = NULL;
n = h;
while(n != NULL)
{
cout << n->data << endl; // EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
n = n->next;
}
return 0;
}
|
The problem is here in this while loop
1 2 3 4 5 6
|
n = h;
while(n != NULL)
{
cout << n->data << endl;
n = n->next;
}
|
some other variations I have tried are:
|
while(n->next != 0) //and NULL
|
|
while(n) // Just n, any value = true, NULL = false.(maybe?)
|
Thank you again for your time and help.
funny thing is that it worked a couple of times but now nothing.