logan
logan

Reputation: 11

how to delete a dynamically allocated 2d array?

#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];
}

I used a double pointer to create a 2d array in heap.The output before and after "delete []arr" is same. what is the mistake here and how does "delete" works in the background?

Upvotes: 0

Views: 238

Answers (2)

Ted Lyngmo
Ted Lyngmo

Reputation: 117238

You should preferably avoid the problem by using smart pointers:

#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';
}

Upvotes: 2

another_CS_guy
another_CS_guy

Reputation: 682

You are deleting array of pointers, not the actual 1D arrays.

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

Upvotes: 2

Related Questions