Home > Blockchain >  Segmentation Fault while getting input from 2D vector
Segmentation Fault while getting input from 2D vector

Time:12-01

I get a segmentation fault when I run the code below.

int main()
{

    int R, C, val;
    cin>>R>>C;
    vector<vector<int>> a;
    for(int i = 0; i < R; i  )
    {
        for(int j = 0; j < C; j  )
        {
             cin>>val;
             a[i].push_back(val);
        }
    }

But when I change it to this, it seems to work. What is the reason?

int main()
{

    int R, C, val;
    cin>>R>>C;
    vector<vector<int>> a;
    for(int i = 0; i < R; i  )
    {
        vector<int>temp;
        for(int j = 0; j < C; j  )
        {
             cin>>val;
             temp.push_back(val);
        }
        a.push_back(temp);
    }

I get the same fault no matter what the value of R and C is kept.

CodePudding user response:

You have never told what is the size of vector<vector<int>>, and you try to access a[i].

You have to resize the vector.

int main()
{

    int R, C;
    std::cin >> R >> C;
    std::vector<std::vector<int>> a(R, std::vector<int>(C));
    for(int i = 0; i < R; i  )
    {
        for(int j = 0; j < C; j  )
        {
             std::cin >> a[i][j]; //because we resize the vector, we can do this
        }
    }
}
  • Related