Hi, I am having a problem with returning a 2d array back to the main in my program. The program reads in a matrix from a file, then it has to multiply etc, however i cannot get the print function to work since the array that is made in the load function is passed back to the main. Here is my code, i am being told that the array i want to print is undefined. I cannot change any of the public member functions, however i can add to the private, but i dont see how that would help me print.
matrix.h
#include <iostream>
#include <fstream>
using namespace std;
#ifndef _matrix_H_
#define _matrix_H_
class matrix
{
public:
matrix();// constructor
matrix(const matrix&);// copy constructor
~matrix();// destructor
bool multiply(const matrix&, const matrix&);
bool isequal(const matrix&);
bool copy(matrix&);
bool load(istream&);
void print(ostream&);
bool isset() const;
void getrowscols(int&, int&) const;
private:
int rows;// number of rows
int cols;// no of columns
float** data;// 2 dimensional array
};
#endif
main.cpp
#include <iostream>
#include <fstream>
#include "matrix.h"
using namespace std;
int main()
{
char filename[50];
matrix* ob;
ob = new matrix();
matrix ob2;
cout << "Enter filename to open: " << endl;
cin >> filename;
fstream ins;
ins.open(filename, ios::in | ios::out);
ob2.load(ins);
ob2.print(ins);
ins.close();
return 0;
}
matrix.cpp
#include <iostream>
#include <fstream>
#include "matrix.h"
using namespace std;
matrix::matrix()
{
rows = 0;
cols = 0;
data = new float *[rows];
for(int i = 0; i < rows; i++)
*(data+i) = new float [cols];
}
matrix::matrix(const matrix& p)
{
rows = p.rows;
cols = p.cols;
data = new float *[rows];
for(int j = 0; j < rows; j++)
*(data+j) = new float [cols];
for(int i = 0; i < rows; i++)
for(int j = 0; j < cols; j++)
*(*(data+i)+j) = *(*(p.data+i)+j);
}
matrix::~matrix()
{
for(int i = 0; i < rows; i++)
delete [] *(data+i);
delete [] data;
}
bool matrix::load(istream& ins)
{
ins >> rows >> cols; //read in rows and columns
float** array = new float*[rows]; //create matrix
if (array != NULL)
{
for (int i = 0; i < rows; i++)
{
array[i] = new float[cols];
}
}
for (int i = 0; i < rows; i++) //read in data
{
for (int j = 0; j < cols; j++)
{
ins >> array[i][j];
}
}
return array;
return true;
}
void matrix::print(ostream& ins)
{
for(int i = 0; i < rows; i++) //print function
{
for(int j = 0; j < cols; j++)
{
ins << " " << array[i][j];
}
cout << endl;
}
}