c++ - Deallocating memory in a 2D array -


suppose have:

int** myarray = new int*[100]; for(int = 0; < 100; i++){     myarray[i] = new int[3]; } 

what appropriate way deallocate array (which method below, if either correct way so)?

1.

delete[] myarray; 

2.

for(int = 0; < 100; i++){     for(int j = 0; j < 3; j++){         delete myarray[i][j];     } } delete[] myarray; 

intuitively seems should 2. since want of memory allocated deleted, i'm not sure.

you used 1 loop create it, should use 1 loop delete it. order reversed order of allocation:

for(int = 0; < 100; i++)     delete [] myarray[i];              // delete "rows" in every "column"  delete [] myarray;                     // delete "columns" 

moreover:

  1. is deleting one-dimensional dynamically allocated array - used delete "rows" , "columns" above.

  2. only resembles how 1 delete 2d array of pointers e.g.:

    int*** myarray = new int**[100];   // (1)  for(int = 0; < 100; i++) {     myarray[i] = new int*[3];      // (2)      for(int j = 0; j < 3; j++)         myarray[i][j] = new int(); // (3) }  for(int = 0; < 100; i++) {     for(int j = 0; j < 3; j++)         delete myarray[i][j];      // (3)      delete [] myarray[i];          // (2) }  delete [] myarray;                 // (1) 

    you can see "reversed" nature of it.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -