I am currently performing the following exercise:
Generic Matrix Class (15 pt)
a) Create a Matrix class, it should contain storage for M * N double type numbers. As before, when choosing your storage method, it is often useful to know that we will use the data for the future. In matrix operations, we are going to access different matrix elements based on their column and / or row, so itβs useful to arrange the elements of the matrix as an array. In addition, we will need to resize the data stored in the matrix, so it must be dynamically allocated.
b) Create constructors for the matrix.
Create the following three constructors: Matrix () β’ Default constructor, should initialize the matrix to an invalid state.
Explicit matrix (unsigned int N) β’ Must construct a valid matrix NxN, initialized as a identity matrix. (The explicit keyword is missing in, but should be used here.)
Matrix (unsigned int M, unsigned int N) β’ Must construct a valid MxN Matrix initialized as a zero matrix. (All elements are zero.)
~ Matrix () β’ Matrix destructor, should delete any dynamically allocated memory.
My class is this:
class Matrix{ private: int rows; int columns; double* matrix; public: Matrix(); explicit Matrix(int N); Matrix(int M, int N); ~Matrix(); };
And the rest of my code:
Matrix::Matrix(){ double * matrix = NULL; } Matrix::Matrix(int N){ double * matrix = new double[N * N]; this->rows = N; this->columns = N; for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ if(i==j) matrix[i * N + j] = 1; else matrix[i * N + j] = 0; } } } Matrix::Matrix(int M, int N){ double * matrix = new double[M * N]; this->rows = M; this->columns = N; for(int i = 0; i < M; i++){ for(int j = 0; j < N; j++) matrix[i * N + j] = 0; } } Matrix::~Matrix(){ delete [] matrix; }
Did I create dynamic array and constructors correctly? Subsequently, I will try to create three different arrays using three different constructors. How to do it? If I try something like this
Matrix::Matrix(); Matrix::Matrix(3);
or
Matrix::Matrix(3,4)
I get the following error:
Unusual exception in 0x773c15de in file Γving_6.exe: 0xC0000005: read access violation location 0xccccccc0.
What am I doing wrong?