Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D vector giving segmentation fault

I am trying to create a 2D array using vector. I have written the following code:

int main() {
    vector< vector<int> > v;

    int i, j;
    for(i=0; i<11; i++)
        for(j=0; j<11; j++)
            v[i].push_back(j);
    for(i=0; i<11; i++) {
        for(j=0; j<11; j++)
            cout<<v[i][j]<<" ";
        cout<<endl;
    }
    return 0;
}

Now I was expecting it to print the numbers 0 to 10, eleven times (each time in a new line). But the code is giving runtime error (segmentation fault). Can anybody please tell me where I am going wrong?

Thanks.

like image 977
Born Again Avatar asked Oct 21 '13 12:10

Born Again


2 Answers

When you declare a vector of anything it doesn't have any elements yet.

Thus:

v[i].push_back(j)

is trying to insert j into a non-existent vector inside the vector v at position i.

In this case as you know the size you should initialize the vector with the number of elements you want in the constructor:

vector<vector<int> > v(11);

That initializes the vector v with 11 empty vectors inside it.

like image 175
Santiago Alessandri Avatar answered Sep 22 '22 11:09

Santiago Alessandri


A segmentation fault occurs when you try to access memory that's not available. Generally when using vectors this means you're accessing an element that's outside of the vector (too high, or too low).

When you use a vector always use the function size() in your for loops as it prevents it from overrunning. You're very likely accessing an element out of the vector size by going 0...10 (that'll return 11 elements, and it's uninitialised there anyway).

like image 40
Nicholas Smith Avatar answered Sep 21 '22 11:09

Nicholas Smith