2014-03-01 104 views
-1

我正在嘗試閱讀矩陣。我看了一下Google,我發現每個人都和我一樣做了類似的事情。它編譯,但是當我介紹第一個位置的值時,它說:分段錯誤:11.我已經在Linux和Mac OSX中試過這段代碼。我得到同樣的錯誤。閱讀矩陣 - 分割錯誤

這是我的函數:

我有這樣的結構:

struct Matri { 
    string idm;   // name of vector 
    int rows; 
    int columns; 
    string id; 
    vector<vector<int> > matrix; 
}; 


void readMatrix(Matri* m){  

    cout << "Introduce the name of the matrix" << endl; 

    cin >> m->idm; 

    cout << "Introduce number of rows: " << endl; 
    cin >> m->rows; 
    cout << "Introduce number of columns: " << endl; 
    cin >> m->columns; 

    m->matrix.resize(m->rows*m->columns); 
    cout << "Size: " << m->matrix.size() << endl; 

    for (int i = 1; i <= m->rows; i++){ 
     for (int j = 1; j <= m->columns; j++){ 
      cout << "Size of matrix: " << m->matrix.size() << endl; 
      cout << "Introduce values for position: " << i << ", " << j << endl; 
      cin >> m->matrix[i][j]; //THIS IS WHAT DOES NOT WORK. It says Segmentation Fault 11. 
     } 
    } 
} 

非常感謝事先!

回答

1

您的循環應該從0到n - 1,而不是從1到n。見this

+0

感謝您的回答,但我有同樣的問題,甚至改變這種! – user3369375

+0

@ user3369375 ...另一個問題是,你沒有提供足夠的信息在你的問題! –

0

這裏

m->matrix.resize(m->rows*m->columns); 

你讓m->rows*m->columns載體,每一個都是空的向量。
崩潰是由您嘗試訪問這些空向量中的元素引起的。

你需要的東西是這樣的:

m->matrix.resize(m->rows); 
for (auto i = m->matrix.begin(); i != m->matrix.end(); ++i) 
{ 
    i->resize(m->columns); 
} 
+0

非常感謝!這是做到這一點的方法! – user3369375