Segmentation Fault Error Dealing with Matrices (Arrays) - c++

I'm trying to reference a 2D array object I've constructed, but for whatever reason I'm getting a segmentation fault and I'm having trouble figuring out the cause. So far I've deduced that the error lies in my operator<< function, but I can't figure out what to change.
main.cpp:
int main() {
My_matrix m1(3, 2);
cout << "Before" << endl;
m1(0,0) = 1; //causes segfault
cout << "After" << endl;
m1(0,1) = 2; //causes segfault
m1(1,0) = 3; //causes segfault
m1(1,1) = 4; //causes segfault
m1(2,0) = 5; //causes segfault
m1(2,1) = 6; //causes segfault
cout << "Checkpoint 1" << endl;
My_matrix m2(); //works
cout << "Checkpoint 2" << endl;
cout << m1.number_of_rows() << endl; //works
cout << "Checkpoint 3" << endl;
cout << m1; //Segfault
cout << "Checkpoint 4" << endl;
cout << m1; //Segfault
cout << "Checkpoint 5" << endl;
cout << m2; //Segfault
cout << "Checkpoint 6" << endl;
}
My_matrix.cpp:
#include "My_matrix.h"
#include <stdexcept>
My_matrix::My_matrix()
{
n = 0;
m = 0;
ptr = nullptr;
}
My_matrix::My_matrix(int n1, int m1)
{
n = n1;
m = m1;
ptr = new int*[n];
for(int i = 0; i < n; i++) {
ptr[i] = new int[m];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ptr[i][j] = 0;
}
}
}
My_matrix::My_matrix(const My_matrix& mat)
{
this->n = mat.n;
this->m = mat.m;
ptr = new int*[n];
for(int i = 0; i < n; i++) {
ptr[i] = new int[m];
}
//----- copy elements over to new matrix -----//
for (int i = 0; i < mat.n; i++) {
for (int j = 0; j < mat.m; j++) {
this->ptr[n][m] = mat.ptr[n][m];
}
}
}
My_matrix::~My_matrix()
{
clear();
}
My_matrix& My_matrix::operator=(const My_matrix& mat)
{
clear();
this->n = mat.n;
this->m = mat.m;
ptr = new int*[n];
for(int i = 0; i < n; i++) {
ptr[i] = new int[m];
}
//----- copy elements over -----//
for (int i = 0; i < mat.n; i++) {
for (int j = 0; j < mat.m; j++) {
this->ptr[n][m] = mat.ptr[n][m];
}
}
}
int My_matrix::number_of_rows() const
{
return n;
}
int My_matrix::number_of_columns() const
{
return m;
}
int* My_matrix::operator()(int i) const
{
return ptr[i];
}
int& My_matrix::operator()(int i, int j) const
{
return ptr[n][m];
}
int& My_matrix::operator()(int i, int j)
{
return ptr[n][m];
}
int& My_matrix::elem(int i, int j) const
{
if (i < 0 || i >= n) throw out_of_range("Out of range");
if (j < 0 || j >= m) throw out_of_range("Out of range");
return ptr[n][m];
}
int& My_matrix::elem(int i, int j)
{
if (i < 0 || i >= n) throw out_of_range("Out of range");
if (j < 0 || j >= m) throw out_of_range("Out of range");
return ptr[n][m];
}
void My_matrix::clear()
{
for (int i = 0; i < n; i++) {
delete[] ptr[i];
}
delete[] ptr;
n = 0;
m = 0;
}
ostream& operator<<(ostream& out, const My_matrix& mat)
{
for (int i = 0; i < mat.number_of_rows(); i++) {
for (int j = 0; j < mat.number_of_columns(); j++) {
out << mat(i, j) << " "; //This line is the culprit ****
}
out << endl;
}
return out;
}

As hinted at by #WhozCraig and #O'Neil in the comments, I had a few typos in my code which referred to indices that were not in bounds of the matrix I had created. Rather than using the iterators/function arguments, I used n and m, which represent the size of the matrix, which is obviously one larger than the largest index. Examples include:
int& My_matrix::elem(int i, int j) const
{
if (i < 0 || i >= n) throw out_of_range("Out of range");
if (j < 0 || j >= m) throw out_of_range("Out of range");
return ptr[n][m]; //<--- should be return ptr[i][j];
}
as well as
My_matrix::My_matrix(const My_matrix& mat)
{
this->n = mat.n;
this->m = mat.m;
ptr = new int*[n];
for(int i = 0; i < n; i++) {
ptr[i] = new int[m];
}
//----- copy elements over to new matrix -----//
for (int i = 0; i < mat.n; i++) {
for (int j = 0; j < mat.m; j++) {
this->ptr[n][m] = mat.ptr[n][m]; //<--- should be this->ptr[i][j] = mat.ptr[i][j];
}
}
}
By correcting these discrepancies my issue was resolved.

Related

Magic Number output

Alright so I have created this code. However, when i run it, it stops when it displays 104 for the counter??? I am so frustrated because I don't know how this could happen. The purpose of the code is to do the typical magic number output where the rows all add up to the same thing, the columns all add up to the same thing, and the diaganols all add up to the same thing. I believe the functions to do these calculations are correct, but the counter keeps stopping short of the 10000 attempts I am trying to do.
#include <iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
void getrandom();
void insertnumber(int n);
bool magic();
void create();
const int rows = 3;
const int cols = 3;
int arr[rows][cols] = { {0,0,0}, {0,0,0} , {0,0,0} };
int main() {
int counter = 0;
do
{
counter++;
cout << counter << endl;
getrandom();
if (counter == 100000)
break;
} while (!magic());
create();
cout << "It took " << counter << " tries." << endl;
return 0;
}
void getrandom() {
int n = 0;
const int size = 9;
int oldnum[size];
for (int i = 0; i < rows * cols; i++) {
oldnum[i] = 0;
}
srand(time(NULL)); // had to import the new libraries to use this
bool used = true;
for (int i = 0; i < size; i++) {
do
{
used = true;
n = rand() % 9 + 1;
if (oldnum[n - 1] == 0)
{
oldnum[n - 1] = n;
used = false;
}
} while (used);
insertnumber(n);
}
}
void insertnumber(int n) {
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
if (arr[i][j] == 0) {
arr[i][j] = n;
return;
}
}
}
}
bool magic() {
int rowsum = arr[0][0] + arr[0][1] + arr[0][2];
for (int i = 1; i < cols; i++)
{
if (arr[i][0] + arr[i][1] + arr[i][2] != rowsum)
return false;
}
for (int j = 0; j < rows; j++)
{
if (arr[0][j] + arr[1][j] + arr[2][j] != rowsum)
return false;
}
if (arr[0][0] + arr[1][1] + arr[2][2] != rowsum)
return false;
if (arr[0][2] + arr[1][1] + arr[2][0] != rowsum)
return false;
return true;
}
void create() {
{
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
}
You can try using a debugger for such problems.
I think you code crashes because of this:
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
It looks like you mean j < cols here :)
Check line 76. When I compile and run the code, line 76 is where the exception is thrown.
This line specifically
arr[i][j] = n;
It seems your insertnumber() function is the culprit.

overloading the addition and multiplication operators for the matrix class

I implement the overloading of the addition and multiplication operators for the matrix class. I can't understand where the error is, or rather, I guess that there is an error in the declaration of operators, but I have no idea how to fix it specifically.
Can someone suggest a good book on object oriented programming. I feel that I am clearly lacking information
#include <iostream>
using namespace std;
template <typename T>
class MATRIX
{
private:
T** M;
int m;
int n;
public:
MATRIX()
{
n = m = 0;
M = nullptr;
}
MATRIX(int _m, int _n)
{
m = _m;
n = _n;
M = (T**) new T * [m];
for (int i = 0; i < m; i++)
M[i] = (T*)new T[n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
M[i][j] = 0;
}
MATRIX(const MATRIX& _M)
{
m = _M.m;
n = _M.n;
M = (T**) new T * [m];
for (int i = 0; i < m; i++)
M[i] = (T*) new T[n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
M[i][j] = _M.M[i][j];
}
T GetMij(int i, int j)
{
if ((m > 0) && (n > 0))
return M[i][j];
else
return 0;
}
void SetMij(int i, int j, T value)
{
if ((i < 0) || (i >= m))
return;
if ((j < 0) || (j >= n))
return;
M[i][j] = value;
}
void Print(const char* ObjName)
{
cout << "Object: " << ObjName << endl;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
cout << M[i][j] << "\t";
cout << endl;
}
cout << "---------------------" << endl << endl;
}
MATRIX operator=(const MATRIX& _M)
{
if (n > 0)
{
for (int i = 0; i < m; i++)
delete[] M[i];
}
if (m > 0)
{
delete[] M;
}
m = _M.m;
n = _M.n;
M = (T**) new T * [m];
for (int i = 0; i < m; i++)
M[i] = (T*) new T[n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
M[i][j] = _M.M[i][j];
return *this;
}
MATRIX operator+(const MATRIX& _M) {
MATRIX M6(_M.n, _M.m);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
M6.M[i][j] = _M.M[i][j]+this-> M[i][j];
}
return M6;
}
MATRIX operator*(const MATRIX& _M) {
MATRIX M5(_M.n, _M.m);
for (int i = 0; i < _M.n; i++)
{
for (int j = 0; j < _M.m; j++)
{
for (int k = 0; k < m; k++)
{
M5.M[i][j] += M[i][k]*_M.M[k][j];
}
}
}
return M5;
}
bool operator ==(const MATRIX& _M) {
return this->n == _M.n && this->m == _M.m;
}
bool operator !=(const MATRIX& _M) {
return !(this->n == _M.n && this->m == _M.m);
}
~MATRIX()
{
if (n > 0)
{
for (int i = 0; i < m; i++)
delete[] M[i];
}
if (m > 0)
delete[] M;
}
};
void main()
{
MATRIX<int> M(2, 3);
M.Print("M");
int i, j;
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++)
M.SetMij(i, j, i + j);
M.Print("M");
MATRIX<int> M2 = M;
M2.Print("M2");
MATRIX<int> M3;
M3 = M;
M3.Print("M3");
MATRIX<int> M4;
M4 = M3 = M2 = M;
M4.Print("M4");
////////////////////////
bool result = M == M3;// ==
if (result == 1) {
cout << "true";
}
else if (result == 0) {
cout << "false";
}
cout << endl << "---------------------" << endl << endl;
//////////////////////////
bool result1 = M != M3;// !=
if (result1 == 1) {
cout << "true";
}
else if (result1 == 0) {
cout << "false";
}
cout << endl << "---------------------" << endl << endl;
MATRIX<int> M1;
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++)
M1.SetMij(i, j, i + j);
M1.Print("M1");
M.Print("M");
MATRIX<int> M6 = M + M1;
M6.Print("M");
MATRIX<int> M5 = M * M1;
M5.Print("M");
}```
thanks in advance
[enter image description here][1]
[1]: https://i.stack.imgur.com/TjEOp.png
I belive that std::vector is better
MATRIX() {}
MATRIX(int r, int c) : M(r * c, T()) , rows(r), cols(c) { }
// Does not need copy constructor
// Does not need operator =
// Does not need destructor
also you can proxy row and cols to overload []
MATRIX<int> x(3,3);
x[2][2] = 10;
also a generating function is welcome
template<typename GenT> void generate( GenT gen ) {...}
https://godbolt.org/z/dK6Tqc

Access violation reading location - creating matrix class

This is supposed to be my HW in OOP course. SO i asked to create matrix class. Code works fine - all methods and new operands works fine BUT when my D`tor is empty and when i write there code to free memory i get this error. Thanks for help
int main()
{
MyMatrix m1(3, 3);
MyMatrix m2(3, 3);
MyMatrix res(3, 3);
m1.Set();
m2.Set();
cout << m1;
cout << m2;
res = m1 + m2;
cout << res;
}
CPP
MyMatrix::MyMatrix(int row, int col) // C`tor with specific data
{
n = row;
m = col;
matrix = new int* [n]; // Memory allocation for rows
for (int i = 0; i < n; i++)
{
matrix[i] = new int[m]; // Memory Allocation for columns
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = 0;
}
}
}
MyMatrix::~MyMatrix() // Default d`tor
{
for (int i = 0; i < n; i++)
{
delete[] matrix[i];
}
delete[] matrix;
}
void MyMatrix::Set()
{
cout << "Enter new row" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> matrix[i][j];
}
if (i != (n - 1))
{
cout << "Enter new row" << endl;
}
}
}
ostream& operator<<(ostream& out, const MyMatrix& matrix)
{
for (int i = 0; i < matrix.n; i++)
{
//run in loop on every column.
for (int j = 0; j < matrix.m; j++)
//print value with a space.
out << matrix.matrix[i][j] << "t";
//at the end of every row jump line.
out << endl;
}
out << endl;
return out;
}
MyMatrix& MyMatrix::operator= (const MyMatrix& mat1)
{
n = mat1.n;
m = mat1.m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = mat1.matrix[i][j];
}
}
return *this;
}
const MyMatrix MyMatrix::operator+(const MyMatrix& mat1) const
{
MyMatrix temp(n, m);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
temp.matrix[i][j] = matrix[i][j] + mat1.matrix[i][j];
}
}
return temp;
}
H file
class MyMatrix
{
private:
int **matrix;
int n, m;
public:
MyMatrix(int a, int b);
~MyMatrix();
void Set();
const MyMatrix operator+ (const MyMatrix& mat1) const;
MyMatrix& operator= (const MyMatrix& mat1);
friend ostream& operator<<(ostream& out, const MyMatrix& matrix);
};

access violation writing location c++ for Gaussian Elimination

I am working on a code for gaussian reduction, but for some reason I am getting the error:
Exception thrown at 0x00A9F6DF in Excersise-7-3.exe: 0xC0000005: Access violation writing location 0xFDFDFDFD.
at S[h][0] = i; (line 147)
I cant seem to resolve this. What should I do? How can I prevent this from happening in the future?
#include "stdafx.h"
#include "Gauss.h"
#include <fstream>
Gauss::Gauss()
{
x.resize(v.size());
vector<double>::iterator it;
for (it = x.begin(); it != x.end(); it++)
{
v[*it] = 0;
}
S = new double*[m];
for (int i = 0; i < m; i++)
{
S[i] = new double[3];
for (int j = 0; j < 3; j++)
{
S[i][j] = 0;
}
}
}
Gauss::~Gauss()
{
}
bool Gauss::read_vector(string filename)
{
ifstream in;
in.open(filename);
if (in.fail())
{
cout << "File could not be opened." << endl;
return false;
}
in >> size;
for (int i = 0; i < size; i++)
{
int y;
in >> y;
v.push_back(y);
}
in.close();
return true;
}
bool Gauss::read_matrix(string filename)
{
ifstream in;
in.open(filename);
if (in.fail())
{
cout << "File could not be opened." << endl;
return false;
}
in >> m;
in >> n;
A = new double *[m];
for (int i = 0; i < m; i++)
{
A[i] = new double[n];
for (int k = 0; k < n; k++)
{
in >> A[i][k];
}
}
in.close();
return true;
}
void Gauss::print_vector()
{
for (int i = 0; i < size; i++)
cout << v[i] << endl;
}
void Gauss::print_matrix()
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cout << A[i][j] << " ";
}
cout << endl;
}
}
void Gauss::elimination(int &i, int &k)
for (int j = 0; j < m - 1; j++)
{
if(j != i)
{
double fraction = A[j][k] / A[i][k];
for (int l = 0; l < n; l++)
{
A[j][l] = A[j][l] - fraction*A[i][l];
v[j] = v[j] - fraction*v[i];
}
}
}
}
void Gauss::row_swap(int &i, int &k)
{
double sub;
for (int j = 0; j < n; j++)
{
sub = A[i][j];
A[i][j] = A[k][j];
A[k][j] = sub;
}
{
sub = v[i];
v[i] = v[k];
v[k] = sub;
}
}
void Gauss::reduction()
{
int h = 0;
int i = 0;
int k = 0;
while (i != m || k != n)
{
if (A[i][k] != 0)
{
elimination(i, k);
S[h][0] = i;
S[h][1] = k;
S[h][2] = A[i][k];
h++;
cout << h;
}
else
{
for (int j = i + 1; j < m; j++)
{
if (A[j][k] > 0)
{
row_swap(i, k);
elimination(i, k);
S[h][0] = i;
S[h][1] = k;
S[h][2] = A[i][k];
h++;
}
else
{
k++;
}
}
}
i++;
k++;
}
}
void Gauss::solution()
{
for (int j = 0; j < m; j++)
{
x[S[j][1]] = v[S[j][0]] / S[j][2];
}
}

C++ OOP - Arrays (matrices) multiplication, deleting object [duplicate]

This question already has answers here:
What is The Rule of Three?
(8 answers)
Closed 7 years ago.
I am writing simple C++ application to multiply two matrices. Yes, I am aware this version doesn't check e.g. whether number of rows is greater than zero.
I can create two objects using a default constructor and I can create third object (a result of multiplication of two previous objects of the same class). I can't however correctly delete this third object. When I try, an "Access violation reading location" exception is throw. Can you tell me what am I missing? Is there something I forget to initialize? This exception is only thrown when using myThirdFunction.
Any other advice on making this code better is welcome :)
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
class MyArray
{
int Variable1 = 0;
int Variable2 = 0;
float ** myArray;
public:
MyArray() : Variable1(0), Variable2(0){ myFunction(); }
MyArray (int variable1, int variable2) : Variable1(variable1):
Variable2(variable2){ myFunction(); }
MyArray(const MyArray &myArrayA, const MyArray &myArrayB) :
Variable1(myArrayA.Variable1), Variable2(myArrayB.Variable2)
{ myThirdFunction(myArrayA, myArrayB); }
MyArray(const MyArray &myArray)
{ Variable1=myArray.Variable1; Variable2 = myArray.Variable2;
this->myArray =myArray.myArray; }
void myFunction() {
cin >> Variable1;
cin >> Variable2;
myArray = new float*[Variable1];
myOtherFunction();
}
void myOtherFunction() {
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
myArray[i][j] = rand() % (10 - 0) + 0;
}
}
void myThirdFunction(MyArray myArrayA, MyArray myArrayB)
{
Variable1 = myArrayA.Variable1;
Variable2 = myArrayB.Variable2;
myArray = new float*[Variable1];
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
{
float tempVariable = 0;
for (int q = 0; q < myArrayA.Variable2; ++q)
{
tempVariable += myArrayA.myArray[i][q] * myArrayB.myArray[q][j];
}
myArray[i][j] = tempVariable;
}
}
}
void displayMyArray() {
for (int i = 0; i < Variable1; ++i)
{
for (int j = 0; j < Variable2; ++j)
cout << myArray[i][j] << '\t';
cout << endl;
}
}
~MyArray() {
for (int i = 0; i < Variable1; ++i)
{
delete[] myArray[i];
}
delete[]myArray;
}
};
int main(){
srand(time(0));
MyArray myArrayA;
myArrayA.displayMyArray();
cout << endl;
MyArray myArrayB;
myArrayB.displayMyArray();
cout << endl;
MyArray myArrayC(myArrayA, myArrayB);
myArrayC.displayMyArray();
getchar();
getchar();
return 0;
}
Thanks :)
The member myArray is a pointer, and in your copy constructor you just copy the pointer without creating a new array. Because myThirdFunction takes both arguments by value, it creates two copies of the original objects. And because the copy constructor doesn't create a new value, when those two copies go out of scope at the end of the function, the original pointers now point to deallocated memory. Whenever the original two objects are destroyed, the destructor tries to delete memory that was already deleted.
From the beginning, you have this constructor:
MyArray(const MyArray &myArrayA, const MyArray &myArrayB)
{
myThirdFunction(myArrayA, myArrayB); //This call creates two new objects
}
The signature of myThirdFunction being void myThirdFunction(MyArray myArrayA, MyArray myArrayB), you pass by value and create two new copies. That calls the copy constructors for the two parameters:
MyArray(const MyArray &myArray)
{
this->myArray =myArray.myArray; //shallow copy, very bad
}
The new objects now point to the same memory as the originals. So, when they are destroyed at the end of myThirdFunction, the original pointers become garbage. In a broad view, this happens. float* p = new float; delete p; delete p; The solution is to make the copy constructor actually copy the elements, not the pointers:
MyArray(const MyArray &p_copy) //The name confused me so I changed it
{
Variable1 = p_copy.Variable1;
Variable2 = p_copy.Variable2;
myArray new float*[Variable1];
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
myArray[i][j] = p_copy.myArray[i][j];
}
}
In addition, you probably want to pass to myThirdFunction by constant reference.
void myThirdFunction(const MyArray& myArrayA, const MyArray& myArrayB)
I don't see a need to create two temporary objects here.
At the first time this code will works.
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
class MyArray
{
int Variable1;
int Variable2;
float ** myArray;
public:
MyArray() : myArray(NULL), Variable1(0), Variable2(0) // initialize pointers with NULL is important
{
myFunction();
}
MyArray (int variable1, int variable2) : myArray(NULL), Variable1(variable1),
Variable2(variable2)
{
myFunction();
}
MyArray(const MyArray &myArrayA, const MyArray &myArrayB) : myArray(NULL),
Variable1(myArrayA.Variable1), Variable2(myArrayB.Variable2)
{
myThirdFunction(myArrayA, myArrayB);
}
MyArray(const MyArray &myArray)
{
Variable1=myArray.Variable1; Variable2 = myArray.Variable2;
this->myArray =myArray.myArray;
}
void myFunction()
{
cin >> Variable1;
cin >> Variable2;
myArray = new float*[Variable1];
myOtherFunction();
}
void myOtherFunction()
{
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
myArray[i][j] = rand() % (10 - 0) + 0;
}
}
void myThirdFunction(MyArray myArrayA, MyArray myArrayB)
{
// cols of first must be same as rows of second
if (myArrayA.Variable2 != myArrayB.Variable1)
return;
// memory must be cleaned before new array creation
clearArray();
Variable1 = myArrayA.Variable1;
Variable2 = myArrayB.Variable2;
myArray = new float*[Variable1];
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
{
float tempVariable = 0;
for (int q = 0; q < myArrayA.Variable2; ++q)
{
tempVariable += myArrayA.myArray[i][q] * myArrayB.myArray[q][j];
}
myArray[i][j] = tempVariable;
}
}
}
void displayMyArray()
{
for (int i = 0; i < Variable1; ++i)
{
for (int j = 0; j < Variable2; ++j)
cout << myArray[i][j] << '\t';
cout << endl;
}
}
~MyArray()
{
clearArray();
}
// clear memory and deinitialize pointers
void clearArray()
{
if (myArray == NULL)
return;
for (int i = 0; i < Variable1; ++i)
{
delete[] myArray[i];
myArray[i] = NULL;
}
delete[]myArray;
myArray = NULL;
}
};
int main(){
srand(time(0));
MyArray myArrayA;
myArrayA.displayMyArray();
cout << endl;
MyArray myArrayB;
myArrayB.displayMyArray();
cout << endl;
MyArray myArrayC(myArrayA, myArrayB);
myArrayC.displayMyArray();
getchar();
getchar();
return 0;
}
but I strongly recomend you to create proper copy constructor and assignment operator means (operator=) to proper object creation and destruction.
Here I post my own matrix realization to refer you in what way you can approve your code.
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
using namespace std::
class Matrix
{
public:
Matrix();
Matrix(int rowcount,int colcount);
Matrix(int rowcount,int colcount,float* matrix);
Matrix(const Matrix& rhs);
~Matrix();
/////////////////////////////////////////////////////////////
Matrix& operator = (const Matrix& rhs);
Matrix operator + (const Matrix& rhs);
Matrix operator - (const Matrix& rhs);
Matrix operator * (float scale);
Matrix operator * (const Matrix& rhs);
void operator += (const Matrix& rhs);
void operator -= (const Matrix& rhs);
void operator *= (float scale);
void operator *= (const Matrix& rhs);
float operator [] (int offset) const;
float& operator [] (int offset);
friend ostream& operator << (ostream& _str,const Matrix& rhs);
/////////////////////////////////////////////////////////////
void setCols(int cols);
void setRows(int rows);
void setMatrix(float* matrix);
int getCols() const
{
return itsCols;
}
int getRows() const
{
return itsRows;
}
const float* getMatrix() const
{
Invariants();
return itsMatrix;
}
void Invariants() const
{
if ((!(itsCols && itsRows && itsMatrix)) && (itsRows < 0) && (itsCols < 0))
{
cout << "Not allowed action!\n";
getch();
exit(0);
}
}
/////////////////////////////////////////////////////////////
private:
float* itsMatrix;
int itsRows;
int itsCols;
};
Matrix::Matrix()
{
itsRows = 0;
itsCols = 0;
itsMatrix = NULL;
}
Matrix::Matrix(int rowcount,int colcount)
{
itsRows = rowcount;
itsCols = colcount;
itsMatrix = new float[itsRows * itsCols];
Invariants();
}
Matrix::Matrix(int rowcount,int colcount,float* matrix)
{
itsRows = rowcount;
itsCols = colcount;
itsMatrix = new float[itsCols * itsRows];
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
itsMatrix[counter] = matrix[counter];
counter++;
}
}
Invariants();
}
Matrix::Matrix(const Matrix& rhs)
{
itsCols = rhs.getCols();
itsRows = rhs.getRows();
itsMatrix = new float[itsRows * itsCols];
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
itsMatrix[counter] = rhs[counter];
counter++;
}
}
}
Matrix::~Matrix()
{
itsCols = 0;
itsRows = 0;
delete [] itsMatrix;
itsMatrix = NULL;
}
Matrix& Matrix::operator = (const Matrix& rhs)
{
if (&rhs == this)
return *this;
else
{
itsRows = rhs.getRows();
itsCols = rhs.getCols();
delete [] itsMatrix;
itsMatrix = NULL;
itsMatrix = new float[itsRows * itsCols];
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
itsMatrix[counter] = rhs[counter];
counter++;
}
}
return *this;
}
}
float& Matrix::operator [] (int offset)
{
Invariants();
if ((offset > -1) && (offset < itsCols * itsRows))
return itsMatrix[offset];
else
{
cout << "You cann't reach this element!\n";
getch();
exit(0);
}
return itsMatrix[offset];
}
float Matrix::operator [] (int offset) const
{
Invariants();
if ((offset > -1) && (offset < itsCols * itsRows))
return itsMatrix[offset];
else
{
cout << "You cann't reach this element!\n";
getch();
exit(0);
}
return 0;
}
Matrix Matrix::operator + (const Matrix& rhs)
{
Invariants();
if (!((this->itsCols == rhs.getCols()) &&
(this->itsRows == rhs.getRows())))
{
cout << "Cann't perform addiction of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] + rhs[counter];
counter++;
}
}
return temp;
}
Matrix Matrix::operator - (const Matrix& rhs)
{
Invariants();
if (!((this->itsCols == rhs.getCols()) &&
(this->itsRows == rhs.getRows())))
{
cout << "Cann't perform substraction of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] - rhs[counter];
counter++;
}
}
return temp;
}
Matrix Matrix::operator * (float scale)
{
Invariants();
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] * scale;
counter++;
}
}
return temp;
}
Matrix Matrix::operator * (const Matrix& rhs)
{
Invariants();
if (!(itsCols == rhs.getRows()))
{
cout << "Cann't perform multiplication of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,rhs.getCols());
int counter = 0;
float sum = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < rhs.getCols(); j++)
{
for (int k = 0; k < itsCols; k++)
{
sum += itsMatrix[i * itsCols + k] *
rhs[k * rhs.getCols() + j];
}
temp[counter] = sum;
sum = 0;
counter++;
}
}
return temp;
}
void Matrix::operator += (const Matrix& rhs)
{
if (!((this->itsCols == rhs.getCols()) &&
(this->itsRows == rhs.getRows())))
{
cout << "Cann't perform addiction of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] + rhs[counter];
counter++;
}
}
*this = temp;
}
void Matrix::operator -= (const Matrix& rhs)
{
if (!((this->itsCols == rhs.getCols()) &&
(this->itsRows == rhs.getRows())))
{
cout << "Cann't perform substraction of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] - rhs[counter];
counter++;
}
}
*this = temp;
}
void Matrix::operator *= (float scale)
{
Invariants();
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] * scale;
counter++;
}
}
*this = temp;
}
void Matrix::operator *= (const Matrix& rhs)
{
Invariants();
if (!(itsCols == rhs.getRows()))
{
cout << "Cann't perform multiplication of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,rhs.getCols());
int counter = 0;
float sum = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < rhs.getCols(); j++)
{
for (int k = 0; k < itsCols; k++)
{
sum += itsMatrix[i * itsCols + k] *
rhs[k * rhs.getCols() + j];
}
temp[counter] = sum;
sum = 0;
counter++;
}
}
*this = temp;
}
ostream& operator << (ostream& _str,const Matrix& rhs)
{
rhs.Invariants();
int counter = 0;
for (int i = 0; i < rhs.getRows(); i++)
{
for (int j = 0; j < rhs.getCols(); j++)
{
_str << rhs[counter] << "\t";
counter++;
}
_str << endl;
}
return _str;
}
float arr1[] =
{
2, 2, 2,
-1, -3, -5,
16, 8, 24,
8, 0, 16
};
float arr2[] =
{
15,
2,
-4
};
int main()
{
clrscr();
Matrix m1(4,3,arr1);
Matrix m2(3,1,arr2);
cout << "Matrix 1:\n";
cout << m1 << endl;
cout << "Matrix 2:\n";
cout << m2 << endl;
cout << "Matrix 1 * Matrix 2\n";
cout << m1 * m2 << endl;
getch();
cout << "Matrix 1 + Matrix 1\n";
cout << m1 + m1 << endl;
getch();
cout << "Matrix 1 - Matrix 1\n";
cout << m1 - m1 << endl;
getch();
cout << "Matrix 1 * 4\n";
cout << m1 * 4 << endl;
getch();
return 0;
}