'Implementing Matrix class with array of pointers

I made two custom classes: a Vector class(algebraic one, not std::vector), and a Matrix class. I easily implemented Vector class as a array of doubles, i.e i store entries like this:

double *tab = nullptr;
//in constructors
//tab = new double[size]{};

I have a problem with Matrix class though. It is supposed to be a array of pointers to Vectors, i.e:

Vector** tab = nullptr;
//dimensions
int m, n;

What if i simply do not implement it this way, and just do a array of Vectors rather than pointers?

Vector* tab = nullptr 
//...
//destructor looks like this  
Matrix::~Matrix(){
    delete[] tab;
    m = n = 0;
}

The latter seems to be easier in implementation, there is no need to call destructor for every Vector in tab. Am I missing some kind of memory leak? If not why would i ever use the first implementation.



Solution 1:[1]

If not why would i ever use the first implementation.

Probably the primary reason that you might want to use an array of arrays is that it allows you to to turn the row-column notation of a matrix, i.e. m[1][0] into access to the correct offset without having to do any math. If you matrix is a single dimensional array and someone asks for a given row and column you have to compute the 1D offset from the 2D information you've been given.

Of course there are ways around this. For instance, you could declare your matrix like this:

class Matrix {
public:
  double * _values;
  double ** _rows;

  Matrix() {
    _values = new double[16];
    _rows = new double*[4];
    auto start = _values;
    for (int i = 0; i < 4; ++i) {
      _rows[i] = start;
      start += 4;
    }
  }

  ~Matrix() {
    delete[] _rows;
    delete[] _values;
  }
}

Now, you've allocated one block of doubles and one block of double* for your row offsets. If you want to get a given row r and column c you can access it as _rows[r][c] without doing any computation.

Alternatively, you could also construct your Matrix type out of a collection of Vectors rather than the internal value type directly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jherico