So I am trying to figure out how I should properly delete a matrix. I believe the code I have correctly allocates memory and sets it up correctly if I type something like Matrix a(2,2). However, I want to know how to delete Matrix a and only Matrix a if I have many matrices. Assume a proper header file.
You're leaking memory like crazy. You don't need to call calloc() before allocating with new.
How about this?
1 2 3 4 5 6 7 8 9 10 11 12 13
Matrix::Matrix(uint rows, uint cols){
array = newdouble[rows * cols];
std::fill(array, array + rows * cols, 0);
}
Matrix::~Matrix(){
delete[] array;
}
//Note: m[col][row] == array[col + row * cols]
//or: m[col][row] == array[col * rows + row]
//It doesn't matter which one you choose as long as you're consistent.
//You'll need to save the size of the matrix.
I guess I'm a bit confused as far as handling memory goes. So say I have a very simple header file called "Matrix.h"
Matrix.h
class Matrix{
public:
Matrix(uint rows, uint cols);
~Matrix();
How would I write Matrix.cpp to correctly implement these two functions to create and destroy different matrices. So say I type in another program that imports Matrix.cpp:
//assume proper imports and main setup
Matrix a(2,2);
Matrix b(2,1);
~Matrix a;
~Matrix b;
Is this something I can do, how can I do it without leaking memory? Also, I cannot use the array class
I guess what I'm also trying to say is that with your program it seems like you can only make one matrix, I want to be able to make numerous ones for manipulation in the later part of the program. You'll have to forgive me, I'm very beginner level, also what is std::fill?