My task is to create "Matrix" class with methods that overload operators: ==, ^, *. (meaning equation check, exponentiaton of matrix and multipling two matricies with each other). I drafted this code, and when I was trying to test my methods, the only problem that occured is "Critical error detected c0000374". I guess there is memory leak somewhere. I guess it might be some problems with returning pointer of my third matrix, which is result of multiply. I don't understand how to deallocate memory of that matrix.
#include "matrix.h"
#include <math.h>
#include <iostream>
Matrix::Matrix()
: n(1)
, m(1)
{
arr = new double *[n];
for (int i = 0; i < n; i++)
{
arr[i] = new double[m];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
arr[i][j] = 0;
}
}
}
Matrix::Matrix(int n_size, int m_size)
: n(n_size)
, m(m_size)
{
arr = new double *[n];
for (int i = 0; i < n; i++)
{
arr[i] = new double[m];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
arr[i][j] = 0;
}
}
}
Matrix::~Matrix()
{
for (int i = 0; i < n; i++)
{
delete[] arr[i];
delete arr;
}
}
void Matrix::userFillMatrix()
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
std::cout << "Enter " << i+1 << " row "
<< j+1 << " column element" << std::endl;
std::cin >> arr[i][j];
std::cout << std::endl;
}
}
}
void Matrix::showMatrix()
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
std::cout << arr[i][j] << " ";
}
}
std::cout << std::endl;
}
bool Matrix::isEqual(const Matrix &matrix)
{
if ((n != matrix.n) && (m != matrix.m))
{
return false;
}
const double epsilon = 1E-15;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (!(fabs(arr[i][j] - matrix.arr[i][j]) < epsilon))
{
return false;
}
}
}
return true;
}
bool Matrix::operator==(const Matrix &matrix)
{
return isEqual(matrix);
}
Matrix Matrix::multiplyMatrixByANumber(const int num)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
arr[i][j] *= num;
}
}
return *this;
}
Matrix Matrix::operator*(const int num)
{
return multiplyMatrixByANumber(num);
}
Matrix Matrix::operator=(double** resArr)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
arr[i][j] = resArr[i][j];
}
}
return *this;
}
double** Matrix::multiplyMatrixes(const Matrix &matrix)
{
if (m != matrix.n)
{
}
double** res = new double *[n];
for (int i = 0; i < n; i++)
{
res[i] = new double[matrix.m];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < matrix.m; j++)
{
res[i][j] = 0;
for (int k = 0; k < m; k++)
{
res[i][j] += arr[i][k] * matrix.arr[k][j];
}
}
}
return res;
}
double** Matrix::operator*(const Matrix &matrix)
{
return multiplyMatrixes(matrix);
}
Matrix Matrix::exponentiationOfMatrix(const int num)
{
for (int i = 0; i < num; i++)
{
*this = multiplyMatrixes(*this);
}
return *this;
}
Matrix Matrix::operator^(const int num)
{
return exponentiationOfMatrix(num);
}
Error occurs when I'm trying to do this expression:
Matrix a(2,2);
Matrix b(2,2);
Matrix c(2,2);
..
//filling a and b
..
c = a*b;