Hi everyone,
I defined a pointer to pointer (p2p) as:
int **my_list = NULL;
After assigning values to this (p2p).
I want to delete it, but I am confusing several ways as follows:
Assigning it back to NULL is the way to go. int **my_list = NULL;
pointers to pointers like all other datatypes are static, you can't get rid of them. There's no need to get rid of them.
When you do need to worry about having to use delete is when you dynamically allocate memory with new. So something like this: int **my_list = newint*[10];
To delete, delete[] my_list;
Note that if the indexes of the pointer to pointer i.e my_list[0], my_list[1] etc are pointing to something, they need to be separately deleted with regular delete delete my_list[0];
Note that delete ptr does not delete the pointer ptr. Instead it deletes whatever ptr is pointing to.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// If my_list points to an array that has been created with new, and
// each element is pointing to an int that has been created with new ...
constint my_list_length = 5;
int **my_list = newint*[my_list_length];
for (int i = 0; i < my_list_length; ++i)
{
my_list[i] = newint;
}
// ... then you you need to loop through the array and use
// delete on each of the elements before deleting the array.
for (int i = 0; i < my_list_length; ++i)
{
delete my_list[i];
}
delete[] my_list;
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// If my_list points to an array that has been created with new,
// and each element is pointing to a local variable ...
constint my_list_length = 5;
int **my_list = newint*[my_list_length];
int local_var;
for (int i = 0; i < my_list_length; ++i)
{
my_list[i] = &local_var;
}
// ... then you don't need to do anything to delete the local_var because
// it will get destroyed automatically when it goes out of scope, but
// you still need to delete the array that was created with new.
delete[] my_list;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// If my_list points to a local array where each element
// is pointing to an int that has been created with new ...
constint arr_length = 5;
int* arr[arr_length];
for (int i = 0; i < arr_length; ++i)
{
arr[i] = newint;
}
int **my_list = arr;
// ... then you only need to use delete on the array elements.
for (int i = 0; i < arr_length; ++i)
{
delete arr[i];
}
1 2 3 4 5 6 7
// If my_list points to a local array where each
// element is pointing to a local variable ...
int local_var;
int* arr[] = {&local_var, &local_var};
int **my_list = arr;
// ... then you don't need to use delete at all.