I was trying to implement a small sample of a linked-list data type. I created a struct Node which holds a value, a struct List which keeps track of all nodes (in linked list format). Finally a class which is a general datatype of both structs.
When I ran the program, I always got a segment fault error as soon as I reached the step:
item->link[i++] = new Node(input)
Code:
struct Node
{
int val;
Node();
Node(int x);
};
struct List
{
Node *link[20];
List();
};
class pol
{
public:
void read_txt(ifstream &file);
private:
List *item;
};
void pol::read_txt(ifstream &file)
{
int input, i;
i = 0;
file >> input;
cout << "Value read from the file: " << input << endl;
while(input != 0)
{
item.link[i++] = new Node(input);
file >> input;
cout << "Value read from the file: " << input << endl;
}
}
What I am trying to do is, create a new Node with the value of “input” which I get from reading a file. Next, I wanted to create a linked list with all the nodes connected.
The member
itemis never initialised. As far as I can see there’s no reason at all to make it a pointer. Just make itList item;.