Home > database >  Is there any way to delete a dynamically allocated array in another function?
Is there any way to delete a dynamically allocated array in another function?

Time:03-02

I am learning pointers in C . This is the exercise given by my teacher:

6. Duplicate a given array.
int* copyArray(int* arr, int n)

My function:

int* copyArray(int* arr, int n)
{
    int* copy = new int[n];

    for (int i = 0; i < n;   i)
        copy[i] = arr[i];
    return copy; 

}

My main function:

int main()
{
    int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
    int* copyPtr = new int[8];
    copyPtr = copyArray(a, 8);

    for (int i = 0; i < 8;   i)
        cout << copyPtr[i] << " "; 
    delete[] copyPtr;
}

Is there any way that I can delete copy array from the main function? I understand the use of smart pointers but I cant use it in this case because of the prototype given by my teacher.

CodePudding user response:

My suspicion is that you are confused by the usual imprecision when we say "delete a pointer". More correct would be to say delete[] x deletes the array that x points to.

In main you do

copyPtr = copyArray(a, 8);

Now copyPtr does point to the copy of the array. When you write

delete[] copyPtr;

You delete the copy of the array.

What you miss is to delete the initial array you created via int* copyPtr = new int[8]; and because you lost any pointer to it you cannot delete it anymore. You could keep the pointer to that initial array and delete it as well. Though, there is no point in allocating an array just to throw it away and create a new array inside the function. Change your code to

int main()
{
    int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
    int* copyPtr = copyArray(a, 8);

    for (int i = 0; i < 8;   i)
        cout << copyPtr[i] << " "; 
    delete[] copyPtr;
}

PS:

I understand the use of smart pointers but I cant use it in this case because of the prototype given by my teacher.

Your conclusion is not right. Smartpointers can interoperate with raw pointers quite well. You just need to take care with ownership. int* arr is passed as raw pointer. Thats completely fine, because the function does not participate in ownership of that array. It merely reads its values. Raw pointers are for non-owning pointers. If you want to take ownership of the returned pointer you can use a std::unique_ptr<int[]>:

int main()
{
    int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
    auto copy = std::unique_ptr<int[]>(copyArray(a,8));

    for (int i = 0; i < 8;   i) std::cout << copy[i] << " "; 
    // no delete !!! the unique_ptr does that for you
}
  • Related