Can someone please take a look at my code to ensure there aren't any memory leaks or (array) overrides or anything else which could be a bad practice in my code ...

Here's my code:

#include <iostream>

using namespace std;

template <typename T>
void create2DMatrix(int rows, int cols, T **&matrix);
template <typename T>
void destroy2DMatrix(int rows, T **&matrix);

int main()
{
	double ** test; /* Needed for our Dynamic 2D Matrix */
	
	create2DMatrix(2, 1, test); /* Create a 2D Matrix */
	
	test[0][0] = 23.59; /* Put some data in the Matrix */
	
	cout << test[0][0] << endl; /* Print the data on the screen */
	
	destroy2DMatrix(2, test); /* Clean up (destroy our 2D Matrix) */
	
	return 0; /* Exit the program ... */
}
template <typename T>
void create2DMatrix(int rows, int cols, T **&matrix)
{
	/* Create a 2D Dynamic Array / Matrix */
	matrix = new T * [rows];
	for(int i = 0; i < rows; i++)
	{
		matrix[i] = new T[cols];
	}
}
template <typename T>
void destroy2DMatrix(int rows, T **&matrix)
{
	/* Destroy a 2D Dynamic Array / Matrix */
	for(int i = 0; i < rows; i++)
	{
		delete[] matrix[i];
	}
	delete[] matrix;
}

Thanks in advance !

Recommended Answers

All 10 Replies

Bad practice wanted? That's bad practice:
1. C-style 2D array allocation/deallocation functions instead of complete 2D array class with full set of operations.
2. Explicit row parameter in destroy2DMatrix: an erron-prone and inconvenient method.
3. Template function definitions after calls: most of C++ compilers can't process this code.
4. 2D matrix... A matrix is a 2D (2D only) array with specific operators - by matrix definition...
;)

Bad practice wanted? That's bad practice:
1. C-style 2D array allocation/deallocation functions instead of complete 2D array class with full set of operations.
2. Explicit row parameter in destroy2DMatrix: an erron-prone and inconvenient method.
3. Template function definitions after calls: most of C++ compilers can't process this code.
4. 2D matrix... A matrix is a 2D (2D only) array with specific operators - by matrix definition...
;)

Can you suggest me a better method to do this ?

Search Google (or what else) for C++ class matrix.
That's a simple improvisation on the topic (in the public domain;)):

/// @file matrix.h:
struct MatrixError {
    const char* what() const { return "Matrix failure"; }
};
/// Incomplete and ineffective but simple
/// number matrix implementation (it works;)
template <typename T>
class Matrix
{
public:
    Matrix(size_t m, size_t n, const T& ival = 0) {
        std::vector<T> irow(n,ival);
        vRows.resize(m,irow);
    }
    virtual ~Matrix() {}

    size_t rows() const { return vRows.size(); }
    size_t cols() const {
        return rows()?vRows[0].size():0;
    }
    std::vector<T>& operator[](size_t i) { return vRows[i]; }
    const std::vector<T>& operator[](size_t i) const {
        return vRows[i];
    }
    Matrix& operator =(const T& val);
    Matrix& operator +=(const Matrix& m);
    bool operator ==(const Matrix& m) const;
    bool operator !=(const Matrix& m) const {
        return !(*this == m);
    }
protected:
    void checkDims(const Matrix& m) const {
        if (rows() != m.rows() || cols() != m.cols())
            throw MatrixError();
    }
    std::vector<std::vector<T> > vRows; 
};
template<typename T>
Matrix<T>& Matrix<T>::operator=(const T& val)
{
    for (size_t i = 0, m = cols(); i < rows(); ++i)
        vRows[i].assign(m,val);
    return *this;
}
template<typename T>
Matrix<T>& Matrix<T>::operator +=(const Matrix& m) 
{
    checkDims(m);
    for (size_t i = 0; i < rows(); ++i)
    for (size_t j = 0; j < cols(); ++j)
        vRows[i][j] += m[i][j];
    return *this; 
}
template<typename T>
bool Matrix<T>::operator ==(const Matrix& m) const
{
    try { // MatrixError handling example
        checkDims(m);
        for (size_t i = 0; i < rows(); ++i)
        for (size_t j = 0; j < cols(); ++j)
            if (vRows[i][j] != m[i][j])
                return false;
    }
    catch(MatrixError&) {
        return false;
    }
    return true;
}
/// Some sugar...
template<typename T>
std::ostream& operator<<(std::ostream& os, const Matrix<T>& m)
{
    for (size_t i = 0; i < m.rows(); ++i) {
        for (size_t j = 0; j < m.cols(); ++j) {
            if (j) os << ' ';
            os << m[i][j];
        }
        os << '\n';
    }
    return os;
}
/// End of matrix.h...

using std::cout;
using std::endl;

int main()
{
    Matrix<double> m(2,2);
    m = 2009;
    cout << m << endl;

    Matrix<double> one(2,2,1);
    cout << one << endl;
    
    m += one;
    cout << m << endl;

    cout << "m == one\? " << (m==one?"Sure":"Nope") << endl;

	return 0;
}

And what if I implement my own matrix class?

Is it also good if I do the following:
1) Class 'array' (a simple vector):
-> Array is a class which holds a simple 1-dimensional array and the number of elements in the array (in the private section)
-> Overload the '[]' and '=' operators ...

2) Create a class 'matrix' in which I hold the class 'array' ...
-> In this class we create a table of objects from the class 'array'

P.S.: Sorry if my English is bad ...

Hi, I found some (useful:?:) information about 2D-Arrays ...

Actually this is what I need, but could you please take a look at it to ensure the programming style is correct ?
(According to that article my code was right
(except for : Explicit row parameter in destroy2DMatrix: an erron-prone and inconvenient method. , which I absolutely agree with !), or am I wrong ?)

This code (which I took from the link in my previous post) raises some questions:

class Array2D
   {
   public:
       Array2D( size_t rows, size_t cols )
       : iData( new int[rows*cols] )
       , iRows( rows )
       , iCols( cols )
       {
       }

     // Add copy and assignment etc.

     ~Array2D()
     {
         delete [] iData;
     }

     int * operator[]( size_t row )
     {
         return iData+iCols*row;
     }

   private:
       int *   iData;
       size_t  iRows;
       size_t  iCols;
   };

I can't seem to figure out what the following means:

Array2D( size_t rows, size_t cols )
: iData( new int[rows*cols] )
       , iRows( rows )
       , iCols( cols )
       {
       }

It's class Array2D constructor with ctor-initializer. I hope you can see that it's initial member values definition.

It's class Array2D constructor with ctor-initializer. I hope you can see that it's initial member values definition.

Did you mean constructor with 'ctor' ?

OK, thank you very much for all your help, time, and useful advices ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.