C ++ multidimensional array initialization

In C ++, when I want to initialize an array of some length (like integers), I can just write

int* tab;
tab = new int[size];

      

where the size is listed somewhere else. But how do I do it the same way when it comes to multidimensional array? I can't just add other dimensions on the second line because the compiler doesn't like it ...

This is a simple question I think. I need this as I am writing assignment in object oriented programming and the 2D array is a private part of the class to be ... constructed in the constructor (with two dimensions as parameters).

+3


source to share


3 answers


Usage std::vector

is a safe way:

std::vector<std::vector<int>> mat(size1, std::vector<int>(size2));

      

if you really want to use it new

yourself:



int** mat = new int*[size1];
for (std::size_t i = 0; i != size1; ++i) {
    mat[i] = new int[size2];
}

      

And don't forget to clean up resources:

for (std::size_t i = 0; i != size1; ++i) {
    delete [] mat[i];
}
delete[] mat;

      

+3


source


If you can afford std::vector

arrays instead, you can use as syntax:



std::vector< std::vector<int> > matrix(rows, std::vector<int>(columns));

for (int i=0; i<rows; i++) {
    for (int j=0; j<columns; j++) {
        matrix[i][j] = i+j;
    }
}

      

+2


source


If you get the height / width parameters before initializing the array, you can try:

int height = 10;
int width = 10;

//...

int tab[heigth][width];

      

0


source







All Articles