Freeing up memory in a 2D array

Let's pretend that:

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

What is the appropriate way to free this array (which method is below if this is the correct way to do this?)

1.

delete[] myArray;

2.

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

It seems intuitively that we should do something like 2., since we want all the allocated memory to be deleted, but I'm not sure.

+4
source share
2 answers

You used one cycle to create it, you must use one cycle to delete it. The order refers to the distribution order:

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

delete [] myArray;                     // delete all "columns"

Wherein:

  • designed to remove a one-dimensional dynamically allocated array - used to delete the "rows" and "columns" above.

  • , 2D- , :

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

    "" .

+7

for(int i = 0; i < 100; i++)
   delete [] myArray[i];

delete [] myArray;
+2

Source: https://habr.com/ru/post/1611081/


All Articles