Deallocating memory in a 2D array

柔情痞子 提交于 2019-12-19 09:07:10

问题


Suppose we have:

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

What is the appropriate way to deallocate this array (which method below, if either is a correct way to do so)?

1.

delete[] myArray;

2.

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

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


回答1:


You used one loop to create it, you should use one loop to delete it. The order is reversed to the order of allocation:

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

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

Moreover:

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

  2. only resembles how one would delete a 2D array of pointers e.g.:

    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)
    

    You can see the "reversed" nature of it.




回答2:


The right method is

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

delete [] myArray;


来源:https://stackoverflow.com/questions/33053336/deallocating-memory-in-a-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!