Matrix Arithmetic using Vectors in C++ causing segmentation faults

后端 未结 7 1193
执笔经年
执笔经年 2021-01-15 02:37

I\'m having some issues passing vectors to functions. My concern is not with my logic itself, as if I need to adjust later I will. My program requirements state that I must

7条回答
  •  隐瞒了意图╮
    2021-01-15 02:44

    Your global definitions of row,col,matrix, ... is the problem.

    int row=0, col=0;
    vector > matrix(row, vector (col) );
    vector > matrix2(row, vector (col) );
    vector > matrix3(row, vector (col) );
    

    What's happening here is the following: row and col is now 0 and therefore all your matrices now have 0 rows and columns.

    You can fix this by using the vector::resize() function after you get row and col from the user.

    cout<<"Enter the number of rows for each Matrix: "<>row;
    cout<<"Enter the number of columns for each Matrix: "<>col;
    // Resize "matrix"
    matrix.resize(row);
    for(int i = 0; i < row; ++i) matrix[i].resize(col);
    // Repeat for "matrix2" and "matrix3"    
    

    Also, this means you don't have to "initialize" your matrix objects. So now you can just define them as:

    vector > matrix;
    vector > matrix2;
    vector > matrix3;
    

    Note:

    1. Think about using typedef to make your code look better.
    2. You don't need them to be global variables. You are using a vector and your printMatrix and addMatrix functions can call vector::size() to find out the size of your matrix. You should rewrite those functions to take your matrix as an argument (lots of good advice here on that) and then work on them.

提交回复
热议问题