How to declare a multidimensional array using new

Asked

Viewed 208 times

2

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

int* ponteiro = new int[5];

But

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

does not compile ! but

int array[5][5];

works perfectly.

1 answer

1


The best way to declare the array multidimensional 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 dislocate the array:

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

// Desaloca a variável ponteiro
delete ponteiro;

To arrays with a variable dimension, it is possible to use the syntax:

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

And if you are compiling the program to the c++2011 standard (or higher), 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 statement, it is important to always remember to shift memory with delete.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.