Crass - 1 year ago 42

C++ Question

I would like to enter specific values into the matrix using a function, but I keep receiving the segmentation fault due to some error located in the matInit function. I receive this error regardless of whether I set it up as bar.col[i].els[k]=0 ( as I did below) or if I save bar.col[i] as an array and do a for loop with the k values. I feel that the segmentation fault is due to the dimensions not matching up, but I don't see what I am doing wrong. I also have to enter the values through the strutures as that is a requirement for this project.

`#include <iostream>`

#include <cmath>

#include <fstream>

using namespace std;

struct Vector {

float* els;

int len;

};

struct Matrix {

Vector* col;

int ncols; // total number of columns in matrix

};

// Initializer functions for our structures

Vector vecInit(int); // Provided below

Matrix matInit(int,int); // ** You must complete this

// Overloaded operators

Vector operator+(Vector,Vector); // Provided below

Vector operator*(float,Vector); // ** You must write this

Vector operator*(Matrix,Vector); // ** You must write this

istream& operator>>(istream&, Vector&); // Provided below

istream& operator>>(istream&, Matrix&); // ** You must write this

// Other Vector functions

float vecDot(Vector,Vector); // ** You must write this

// main code

// **** This must be left unchanged in your submission *****

int main(void) {

int m,n,nv,nw;

ifstream fin("mat.def");

if (!fin.is_open()) {

cout << "Cannot find file mat.def!" << endl;

}

else {

// Load details of matrix M from file

fin >> m >> n;

Matrix M = matInit(m,n);

fin >> M;

cout << "M is " << m << "x" << n << endl;

}

return 0;

}

// *****************************************************

// Support function definitions

// ** Provided Code. Do not change **

// Vector structure initializer

// *** Partially provided code. Change as needed below ***

// Matrix structure initializer

Matrix matInit(int m, int n) {

Matrix bar;

bar.ncols = n;

bar.col = new Vector[m];

for (int i=0;i<n;i++) {

for (int k=0;k<m;k++) {

bar.col[i].els[k]=0;

}

}

return bar;

}

istream& operator>>(istream& input, Matrix& M) {

int leng=M.col[0].len;

for (int i=0;i<M.ncols;i++) {

for (int k=0;k<leng;k++) {

input >> M.col[i].els[k];

}

}

return input;

}

Answer Source

You must allocate arrays in each vectors before assigning values to their elements.

```
Matrix matInit(int m, int n) {
Matrix bar;
bar.ncols = n;
bar.col = new Vector[n]; // use n instead m for consistency
for (int i=0;i<n;i++) {
bar.col[i].els = new float[m]; // add this line to allocate arrays
for (int k=0;k<m;k++) {
bar.col[i].els[k]=0;
}
}
return bar;
}
```