# Allocating(deallocating) memory for matrix(optimise & critique) (suggestion how to “convert” all for loop to function from algorithm)

``````#include <iostream>
#include <algorithm>

using std::cout;
using std::cin;
using std::endl;
using std::fill;

void DeallocateMatrix(double **&ref, int m) {
if(ref==0) return;
for(int i=0; i<m; i++) {
delete[] ref[i];
ref[i]=0;
}
delete[] ref;
ref=0;
}
void AllocateMatrix(double **&ref, int m, int n) {
try {
ref=new double*[m];
fill(ref, ref+m, static_cast<double*>(0));
try {
for(int i=0; i<m; i++)
ref[i]=new double[n];

for(int i=0; i<m; i++)
fill(ref[i], ref[i]+n, 0);
}
catch(...) {
DeallocateMatrix(ref, m);
throw;
}
}
catch(...) {
throw "ERROR: Allocation failed!\n";
}
}
void PrintMatrix(double const* const*p, int m, int n, char name_of_matrix) {
cout << "Matrix " << name_of_matrix << "..." << endl;
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
cout << p[i][j] << "  ";
}
cout << endl;
}
}
int main() {
cout << "Enter the matrix A format(m x n): ";
int m1, n1;
cin >> m1 >> n1;

cout << "Enter the matrix B format(m x n): ";
int m2, n2;
cin >> m2 >> n2;

double **A(0), **B(0);
try {
AllocateMatrix(A, m1, n1);
AllocateMatrix(B, m2, n2);

PrintMatrix(A, m1, n1, 'A');
PrintMatrix(B, m2, n2, 'B');
}
catch(const char error[]) {
cout << error;
}

DeallocateMatrix(A, m1);
DeallocateMatrix(B, m2);

return 0;
}
``````
-

Write a class that encapsulates matrix.
Make the constructor do any allocation and destructor destroy the memory then write an output/input operator.

What is the point of catching all exceptions here?

``````catch(...) {
throw "ERROR: Allocation failed!\n";
}
``````

This just invalidates the whole point of using exceptions.
If you can not fix the problem then do not catch the exception (unless you are logging then you should immediately re-throw).

Here you have an error. The object is invalid and the code continues to execute (and probably crash hard).

-
that is not point here, i purposely used procedural programming –  Srle Sep 7 '11 at 14:22
@Srle: If you are intentionally doing something that is considered general bad practice for the language then you should explain why. Otherwise my comment stands BAD IDEA –  Loki Astari Sep 7 '11 at 14:26
"ref=NULL" that will be done by function DeallocateMatrix ? –  Srle Sep 7 '11 at 14:39
@Srle: See how hard it is to read when you do it like this. Even I am having a hard time following it. –  Loki Astari Sep 7 '11 at 14:43