I am working on writing a class to define an NxM matrix. A matrix should be printed in the form:
[0 1 2]
[3 4 5]
[6 7 8]
private:
//matrix class member variables
unsigned int rows;
unsigned int cols;
float * data;
// constructor
matrix::matrix(int r, int c)
{
rows=r;
cols=c;
data=new float[r*c];
defaultFill(); //function to set the contents of data to all 0s
}
//print function to output matrix in correct format
void matrix::print()
{
for (int i=0; i<(rows); i++)
{
cout<<"[ ";
for (int j=0; j<cols; j++)
{
cout<<data[(i*rows)+j]<<" ";
}
cout<<"]"<<endl;
}
cout<<"]";
}
The problem that I am having is with the print function. When the matrix is square, it works as desired. However, when the number of rows is greater than the number of columns (like a 4x3 matrix), the shell crashes after outputting "["
When the number of columns is greater than the number of rows (like a 3x4 matrix), the output is:
[1 2 3 4]
[4 5 6 7]
[7 8 9 0]
when it SHOULD be:
[1 2 3 4]
[5 6 7 8]
[9 0 0 0]
I'm having difficulty finding the error(s) in my code and would really appreciate it if someone could help me figure out exactly what I am doing wrong so that I can fix it.