SO for my assignment, I had to make a matrix class, and using pointers, make the user enter a matrix, and then run the program to copy that matrix into another object and display both identical matrices. I have to use pointers for both matrices. Here's the code:
#include <iostream>
#include <fstream>
usingnamespace std;
class matrix
{
private:
int rows;
int cols;
double** matrixPtr;
public:
matrix();
matrix(int, int);
matrix(int, int, double);
matrix& operator =(matrix&);
friend istream& operator >>(istream&,matrix&);
friend ostream& operator <<(ostream&, matrix);
double initial;
//~matrix();
};
istream& operator >>(istream& getdata,matrix& array)
{
if (array.matrixPtr!=0)
{
for (int i = 0; i< array.rows; i++)
{
delete [] array.matrixPtr[i];
}
delete[] array.matrixPtr;
}
getdata >> array.rows >> array.cols;
array.matrixPtr = newdouble* [array.rows];
for (int i = 0; i<array.rows; i++)
{
array.matrixPtr[i] = newdouble[array.cols];
for (int j= 0; j<array.cols; j++)
{
getdata >> array.matrixPtr[i][j];
}
}
return getdata;
}
ostream& operator <<(ostream& showdata, matrix array)
{
for (int i = 0; i<array.rows; i++)
{
for (int j=0; j<array.cols; j++)
{
showdata << array.matrixPtr[i][j] << " ";
}
showdata << endl;
}
return showdata;
}
matrix& matrix::operator =(matrix& array2)
{
if (!array2.matrixPtr==NULL)
{
for (int i = 0; i< array2.rows; i++)
{
delete [] array2.matrixPtr[i];
}
delete[] array2.matrixPtr;
}
array2.rows=rows;
array2.cols=cols;
array2.matrixPtr = newdouble* [array2.rows];
for (int i = 0; i<rows; i++)
{
matrixPtr[i] = array2.matrixPtr[i];
}
for (int i = 0; i<rows; i++)
{
for (int j = 0; j<cols; j++)
{
array2.matrixPtr[i][j] = matrixPtr[i][j];
}
}
return array2;
}
matrix::matrix()
{
rows=0;
cols=0;
matrixPtr=NULL;
}
matrix::matrix(int row, int col)
{
rows= row;
cols=col;
matrixPtr = newdouble*[rows];
for (int i = 0; i<rows; i++)
{
matrixPtr[i] = newdouble[cols];
}
for (int i=0; i<row; i++)
{
for (int j=0; j<col; i++)
{
matrixPtr[i][j]=0.0;
}
}
}
matrix::matrix(int row, int col, double ini)
{
ini = initial;
for (int i=0; i<row; i++)
{
for (int j=0; j<col; i++)
{
matrixPtr[i][j]=initial;
}
}
}
int main()
{
matrix thematrix, matrixreloaded;
cout << "Enter the Number of Rows and Columns: ";
cin >> thematrix;
cout << thematrix;
thematrix = matrixreloaded;
cout << matrixreloaded;
return 0;
}
The problem is in the assignment operator definition, in which the line " array2.matrixPtr[i][j] = matrixPtr[i][j];" gives an error saying "Thread 1: Program received signal: "EXC_BAD_ACCESS" "
Eh thanks man, But I guess that's not the only problem... My program is probably full of bugs... There are other things I'm trying to work around as well... :s like swapping stuff..