Matrix Arithmetic using Vectors in C++ causing segmentation faults

早过忘川 提交于 2019-12-19 10:13:29

问题


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 have separate functions that build the matrices, print the final matrix, and ones to perform the desired mathematical operations. I'm not concerned with help on the math logic.

It seems that I have the "hard' stuff down, for example, creating a vector of a vector, etc, but I'm having trouble passing the vectors to functions etc.

#include <iostream>
#include <iomanip>
#include <vector>

using namespace std;
using std::vector;

void build();
void printMatrix(vector<vector<int> > );
int row=0, col=0;
vector<vector<int> > matrix(row, vector<int> (col) );
vector<vector<int> > matrix2(row, vector<int> (col) );
vector<vector<int> > matrix3(row, vector<int> (col) );

int main(){
build();
addMatrix();
printMatrix(matrix3);
return 0;
}
//====================================================    
void build(){
//currently intended just to build 2x matrices of different increasing data
int k=0, l=5;
cout<<"Enter the number of rows for each Matrix: "<<endl;
cin>>row;
cout<<"Enter the number of columns for each Matrix: "<<endl;
cin>>col;
for( int i = 0; i < row; i++ ) {
    for ( int j = 0; j < col; j++ ){
        matrix[i][j] = k++;
        matrix2[i][j] = l++;
    }
}

I'm using Global Variables, because I want the Rows & Columns to stay the same and in the program, I'm only going to be able to call one of the mathematical functions at at time.

void printMatrix(vector<vector<int> > newMatrix3){
    for ( int i = 0; i < row; i++ ) {
        for ( int j = 0; j < col; j++ )
            cout<< setw ( 3 ) << newMatrix3[i][j] <<' ';
            cout<<'\n';
    }
 }
//=========================================
void addMatrix(){
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++)
            matrix3[i][j]=(matrix[i][j]+matrix2[i][j]);
    }

}

This program compiles 100% so if you see a syntax error it's because my copy + paste messed up. As soon as I enter the dimensions for the matrix, the program crashes with a segmentation fault. I'm very new to C++, so this is very frustrating. I'm also all ears to take suggestions on style/best practice. I have the feeling that my use of global variables is not ideal....but I'm under instructions to make the arithmetic functions as re-usable as possible. Also, I don't think I'm making the best use of functions.

Thank you.


回答1:


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

int row=0, col=0;
vector<vector<int> > matrix(row, vector<int> (col) );
vector<vector<int> > matrix2(row, vector<int> (col) );
vector<vector<int> > matrix3(row, vector<int> (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: "<<endl;
cin>>row;
cout<<"Enter the number of columns for each Matrix: "<<endl;
cin>>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<vector<int> > matrix;
vector<vector<int> > matrix2;
vector<vector<int> > 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.



回答2:


Matrices are created when row and col are zero, so any attempt to access their contents results in a segmentation fault. You need to first read row and col, and then build the matrices. This excludes making them global variables.




回答3:


You're not resizing the vectors/matrices to the dimensions that the user put in - they're stuck at row == 0, col == 0 because that's what the two variables default to.

You'd want to look at vector::resize() to update the dimensions of the vector after the user input.




回答4:


You never add the elements to the matrices, ie. matrix and matrix2 are empty when you call build. You need to size the matrix after your receive the users input.

void build(){
//currently intended just to build 2x matrices of different increasing data
int k=0, l=5;
cout<<"Enter the number of rows for each Matrix: "<<endl;
cin>>row;
cout<<"Enter the number of columns for each Matrix: "<<endl;
cin>>col;
matrix.resize(row);
matrix2.resize(row);
for( int i = 0; i < row; i++ ) {
    matrix[i].resize(col, 0);
    matrix2[i].resize(col, 0);
    for ( int j = 0; j < col; j++ ){
        matrix[i][j] = k++;
        matrix2[i][j] = l++;
    }
}



回答5:


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

This creates the vectors while row and col are still zero, long before you read in the values.




回答6:


You must use push_back to initialize elements of a vector, or you must size the vectors before using [index]= form.




回答7:


Your program segfault because you create matrix with a size of (0,0). When you try to set elements : segfault :)

Suggestions :

  • use a matrix library :)
  • if you want to learn : create a Matrix object that you will create with the correct size
  • please avoid globals !
  • flag your question as homework ;)

For your class try to implement something like :

class Matrix
{
    public:
    Matrix(unsigned rows, unsigned columns);
    void add(const Matrix&)
    void print();

    // etc.
};

my2c



来源:https://stackoverflow.com/questions/6347375/matrix-arithmetic-using-vectors-in-c-causing-segmentation-faults

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!