How to declare a multidimensional array using new

2

How do I declare a multidimensional array using new? A normal array looks like this:

int* ponteiro = new int[5];

But

int* ponteiro = new int[5][5];

Do not compile! but

int array[5][5];

works perfectly.

    
asked by anonymous 29.05.2018 / 19:30

1 answer

1

The best way to declare the multidimensional array is to declare an array of pointers for each level and initialize the level within a looping .

Example for ponteiro[30][100] :

// Declara e cria o primeiro nível como ponteiro duplo de 30 elementos
int **ponteiro = new int*[30];

// Para cada item, cria um vetor de 100 elementos
for(int i=0; i<30; i++)
    ponteiro[i] = new int[100];

And the code to deallocate the array :

// Desaloca cada um dos items
for(int i=0; i<30; i++)
    delete ponteiro[i];

// Desaloca a variável ponteiro
delete ponteiro;

For arrays with a variable dimension, you can use the syntax:

int (*ponteiro)[100] = new int[30][100];

And if you are compiling the program for the c ++ 2011 (or higher) standard, you can directly initialize the internal arrays within an extended list with the syntax (example for [3][2] ):

int **ponteiro = new int*[3]{ new int[2], new int[2], new int[2] };

Regardless of the form of declaration, it is important to always remember to deallocate memory with delete .

    
30.05.2018 / 02:48