提问者:小点点

如何删除一个动态分配的2D数组?


#include<iostream>
using namespace std;
int main(){
 int **arr;
 arr=new int*[3];
 arr[0]=new int [4];
 arr[1]=new int [4];
 arr[2]=new int [5];
 arr[2][0]=20;
 cout << arr[2][0] << endl;
 delete []arr;
 cout << arr[2][0];
}

我使用双指针在堆中创建了一个2D数组,“delete[]arr”前后的输出是相同的。 这里的错误是什么,“删除”在后台是如何工作的?


共2个答案

匿名用户

您正在删除指针数组,而不是实际的一维数组。

    //Free sub-array's first
    for(int i = 0; i < 3; ++i) {
        delete[] arr[i];   
    }
    //Free the array of pointers
    delete[] arr;

匿名用户

您最好使用智能指针来避免这个问题:

#include <iostream>
#include <memory>

int main() {
    std::unique_ptr<std::unique_ptr<int[]>[]> arr = std::make_unique<std::unique_ptr<int[]>[]>(3);
    arr[0] = std::make_unique<int[]>(4);
    arr[1] = std::make_unique<int[]>(4);
    arr[2] = std::make_unique<int[]>(4);
    arr[2][0] = 20;
    std::cout << arr[2][0] << '\n';
}