C++ STL: Unhandled exception while using list

Insert the node at specific position using C++ and its STL feature.


#include<iostream>
#include<conio.h>
#include<list>
#include<iterator>
using namespace ::std;
struct link
{
int data; //data item
link* next; // pointer to link
};
class linklist //list of links
{
link* head; // pointer to first link
public:
void additem(int d, int n); // add data item

};

void linklist::additem(int d, int n)
{
link* temp = new link; // make a new link
temp->data = d; // give it data
temp->next = NULL;
if (n == 1)
{
temp->next = head; // adding node at 1st position
head = temp;
return;
}
link* temp1 = new link;
for (int i = 0; i < n - 2; i++)
{
temp1 = temp1->next; // traversing to next node
}
temp->next = temp1->next;
temp1->next = temp;
}



int main()
{
linklist l1; // making linked list
list<int> l; // l to be list container
ostream_iterator<int>screen(cout, "");

l.push_back(10); // pushing element in
l.push_back(20); // linked list
l.push_back(30);
l.push_back(50);
l.push_back(60);
copy(l.begin(), l.end(), screen); // printing element in list
cout << endl;
l1.additem(40, 4); // adding element at the
copy(l.begin(), l.end(), screen); // specific position
_getch();
return 0;
}

Accepting and printing Linked list, I have done through STL and inserting node at specific position is done through C++ object oriented approach. No error in the program but output is only 10,20,30,50,60. And message is like " Unhandled exception at 0*00CA..... . Access violating reading at location 0*CD..... How to solve this problem ?
You need to step through your addItem function. Seeing as it's successfully printing out the elements in the list i would say your issue is in there.
Topic archived. No new replies allowed.