c++arraysmatrixdynamic-data

How do you dynamically allocate a matrix?


How do you dynamically allocate a 2D matrix in C++? I have tried based on what I already know:

#include <iostream>

int main(){
    int rows;
    int cols;
    int * arr;
    arr = new int[rows][cols];
 }

It works for one parameter, but now for two. What should I do?


Solution

  • A matrix is actually can be represented as an array of arrays.

    int rows = ..., cols = ...;
    int** matrix = new int*[rows];
    for (int i = 0; i < rows; ++i)
        matrix[i] = new int[cols];
    

    Of course, to delete the matrix, you should do the following:

    for (int i = 0; i < rows; ++i)
        delete [] matrix[i];
    delete [] matrix;
    

    I have just figured out another possibility:

    int rows = ..., cols = ...;
    int** matrix = new int*[rows];
    if (rows)
    {
        matrix[0] = new int[rows * cols];
        for (int i = 1; i < rows; ++i)
            matrix[i] = matrix[0] + i * cols;
    }
    

    Freeing this array is easier:

    if (rows) delete [] matrix[0];
    delete [] matrix;
    

    This solution has the advantage of allocating a single big block of memory for all the elements, instead of several little chunks. The first solution I posted is a better example of the arrays of arrays concept, though.