I am trying to implement a linked list with size(defined 10 in this case) items
The code compliles fine but gives a run time error at the bolded comment below.
When i debug it gives the message as given in comment. Can somebody suggest what's going on? Why is the memory not accesible?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
for ( int i = 0; i < size; i++)
{
link t = new Node ((1+rand()%100), 0);
cout << t->info << endl;
if ( i == 0)
head = t;
t = t->next;
}
link m = head;
for ( int j = 0; j < size; j++)
{
cout << m->info; /*///ERROR/////-- An Access Segmentation Fault occured in your program -------------*/
m = m->next;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
staticconstint size = 10;
class Node
{
public:
Node(int a, Node *b){ info = a; next = b;}
int info;
Node* next;
};
typedef Node* link;
int main()
{
srand(time(0));
link head = 0;
for ( int i = 0; i < size; i++)
{
link t = new Node ((1+rand()%100), 0);
cout << t->info << endl;
if ( i == 0)
head = t;
t = t->next;
}
link m = head;
for ( int j = 0; j < size; j++)
{
cout << m->info;
m = m->next;
}
}
Are you sure m->info is set to something sensible? Are you sure head->info is set to something sensible before you copy head into m?
I don't see anything in your code that sets link::info anywhere. You haven't shown us the definition of link::info, nor of the constructor for Node, nor of the copy constructor for link, so we can't possibly know how it's being set.
Edit: Ninja'd.