'Is there any way to delete a dynamically allocated array in another function?
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
