-1

whats wrong with this simple program. I want to create multi list and insert using c++ STL. its giving segmentation fault.

enter image description here

#include <iostream>
#include <list>
using namespace std;
int main(){
        list<int> *l;
        l[0].push_back(1);
        l[10].push_back(12);
        cout<<endl;
        return 0;
}
Rambabu
  • 93
  • 1
  • 8

4 Answers4

4

Why are you using a pointer to a list? You didn't allocate memory for the list. You could use a container to store multiple lists, e.g. std:array for static number of elements or std::vector for dynamic number of elements:

#include <array>
#include <iostream>
#include <list>
#include <vector>
using std::array;
using std::vector;
using std::list;
using std::cout;

int main(){
        std::array<list<int>, 11> l;
        l[0].push_back(1);
        l[10].push_back(12);


        std::vector<list<int>> l2(11);
        l2[0].push_back(1);
        l2[10].push_back(12);
        cout << '\n';
        return 0;
}
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
4

list<int> *l; makes l a pointer to a list<int> but it doesn't actually create a list<int> - and definitely not an array of list<int> which you are trying to access.

Possible solutions.

Plain C fixed size arrays of list<int>:

#include <iostream>
#include <list>

int main() {
    std::list<int> l[11];            // place for 11 list<int>`'s
    l[0].push_back(1);
    l[10].push_back(12);
}

Using the C++ fixed sized std::array:

#include <array>
#include <list>

int main() {
    std::array<std::list<int>, 11> l; // place for 11 list<int>'s
    l[0].push_back(1);
    l[10].push_back(12);
}

Using a C++ std::vector that allows for dynamicially adding more list<int>'s:

#include <list>
#include <vector>

int main() {
    std::vector<std::list<int>> l(11); // starts with place for 11 list<int>'s
    l[0].push_back(1);
    l[10].push_back(12);
}

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
0

list<int> *l; is a pointer to list, it is not initialized, so adding elements to it has undefined behaviour. Either you initialize it to a variable like:

list<int> l;
l.push_back(1);
l.push_back(12);

In this case you can only access the elements that already have data, l[0] or l[1].

Or you need to allocate space to the number of elements you need in your list.

For instance:

list<int> l[20];
l[0].push_back(1);
l[10].push_back(12);
anastaciu
  • 23,467
  • 7
  • 28
  • 53
0

In list<int> *l; is creating a pointer to a list. Before accessing l you need to assign valid address to it.

Something like this,

list<int> l;
list<int> *l2 = &l;
TruthSeeker
  • 1,539
  • 11
  • 24