简体   繁体   中英

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.

You need to resize your matrix before accessing elements:

mat.resize(3);
for( int i=0; i < 3; ++i)
{
  mat[i].resize(2);
}
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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM