Darko Darko - 2 months ago 5
C++ Question

using delete[] in main when new int [] was declared in a function

My first job is this:

"The first function, readNumbers, is to read a set of 10 numbers from std::cin and use them to initialise a dynamically allocated array of int of length 10 (dynamic allocation is on the heap). The function must return a pointer to the array. You may assume that the input will be 10 integer values and nothing else."

which is fine, however i need to then:

"The main function for this problem must call your readNumbers function, then pass the new array to your printNumbers function and finally delete the array."

However i am unsure of how to handle the delete in main, when the new int [] has been declared in a function. here is the relevant parts of my code.

int *readNumbers(){
int * numbers;
numbers = new int [10];

for (int i = 0; i < 10; i++){
int userinput;
cin >> userinput;
*(numbers+i) = userinput;
return numbers;


int main(){

delete[] numbers;


obviously the delete[] request in main is a syntax error, i am unsure of the solution.


You need to assign the result of readNumbers() to a variable, then you can delete it.

int main() {
    int *numbers = readNumbers();
    printNumbers(numbers, 10);
    delete[] numbers;
    return 0;