'How to delete pointer from a dynamic array of pointers at an exact index?

When we have dynamic array of pointers in hand, suppose we want to delete 3rd index of this array and copying the higher pointers down one slot.

Q1: Do we need to delete 3rd element?

Q2: What happens after we make delete aPtr[3] and assigning new pointer to aPtr[3]

Does the code part do what I am trying to do?

'''

A **aPtr = new A*[10];

for(int i=0; i< 10; i++)
{
    aPtr[i] = new A;
}

delete aPtr[3];

for(int i=3; i<9; i++)
{
    aPtr[i] = aPtr[i+1];
}

'''

Another question regardless of the previous one. When we want to delete all the elements in the array of pointers, is the statement "delete [] aPtr;" also required?

'''

A **aPtr = new A*[10];

for(int i=0; i< 10; i++)
{
    aPtr[i] = new A;
}


for(int i=0; i<10; i++)
{
    delete aPtr[i];
}

delete[] aPtr; //<-----Is this line required to free the memory?

'''



Solution 1:[1]

Your code looks good with one exception.

delete aPtr[3];

for(int i=3; i<9; i++)
{
    aPtr[i] = aPtr[i+1];
}

Add this:

aPtr[9] = nullptr;

Otherwise aPtr[8] and aPtr[9] both point to the same place, and later when you delete the whole thing, you'll double-delete that pointer.

Otherwise, it looks good.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joseph Larson