Memory allocation (deletion)

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.

Matrix::Matrix(uint rows, uint cols){
array = (double **)calloc(rows,sizeof(double *));
array = new double*[rows];

for(uint i = 0; i < rows; i++){
array[i] = (double *)calloc(cols,sizeof(double *));
array[i] = new double[cols];
}

for(uint i = 0; i < rows; i++){
for(uint j = 0; j < cols; j++){
array[i][j] = 0.0;
}
}

Matrix::~Matrix(){//What can I do to make this function work correctly? }
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 = new double[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?
'array' is not a class.

I guess what I'm also trying to say is that with your program it seems like you can only make one matrix
The array is assigned to a class member, so you'll have only one per Matrix, but you can create as many Matrixes as you want.

std::fill() is a standard function to initialize a sequence. What I wrote is equivalent to
1
2
3
//std::fill(array, array + rows * cols, 0);
for (double *i = array, *e = array + rows * cols; i != e; ++i)
    *i = 0;
Topic archived. No new replies allowed.