Lyes
Lyes

Reputation: 477

Segmentation fault (core dumped) when initializing a matrix in c++

I'm getting a Segmentation fault (core dumped) error when executing the program that instantiate a class Matrice and creating it in its constructor.

here is my simple code:

#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>

class Matrice{
public:
  std::vector<std::vector<int> > mat;

  Matrice(){
    for(int i=0; i < 3; ++i) {
      for(int j=0; j < 2; ++j) {
        mat[i][j] = rand()%(10-0)+0;
      }
    }
  }
};


int main(){
  Matrice mat1;
  return 0;
}

can someone enlighten me.

Upvotes: 0

Views: 445

Answers (3)

JComputerScience
JComputerScience

Reputation: 165

Matrice(){
    for(int i=0; i < 3; ++i) {
        mat.push_back(std::vector<int>());
        for(int j=0; j < 2; ++j) {
            mat[i].push_back(rand()%(10-0)+0);
        }
    }
}

Edit:

Explanation: vectors require the push_back function call to add an element to the end of the vector and will automatically reallocate space for the vector if it goes over the size originally allocated for the vector. Since it is a vector of vectors, you first need to push back an arbitrary vector, then at each arbitrary vector stored in mat[i], we push_back the random integer value needed.

Upvotes: 2

Jeffrey
Jeffrey

Reputation: 11400

You need to resize your matrix before accessing elements:

mat.resize(3);
for( int i=0; i < 3; ++i)
{
  mat[i].resize(2);
}

Upvotes: 2

flu
flu

Reputation: 556

You are using std::vector incorrectly. Please see https://en.cppreference.com/w/cpp/container/vector/operator_at

The [] operator returns a reference to an existing value. Unlike std::map, it does not insert a new value. Use std::vector::push_back() to add elements to a vector.

Upvotes: 1

Related Questions