1

I have made a function for expanding array, and this function is inside a class.

Because this function creates new_arr and copies all the numbers of array into the new_arr and at the end sets pointer of array with new_arr, I wold like to know how to delete numbers in array becuse I dont need it any more

void Array::bigger() {
    int  new_size = size * 2;
    int *new_arr = new int[new_size];
    for (int f1=0; f1<last; f1++) {
        new_arr[f1] = array[f1];
    }
    this->size = new_size;
    array = new_arr;
}

Thanks

1
  • 5
    delete[] array; before array = new_arr;. You could also use std::copy() to copy array to new_arr. You could also use std::vector<int> and forget about dynamic memory management. Commented Nov 16, 2012 at 11:23

2 Answers 2

4

Assuming this is an exercise, then delete the array before re-assigning to the new one:

delete [] array;
array = new_arr;

In real code, use an std::vector<int> instead of the dynamically allocated array.

Sign up to request clarification or add additional context in comments.

Comments

3

free memory before lose pointer to it:

void Array::bigger() {
    int  new_size = size * 2;
    int *new_arr = new int[new_size];
    for (int f1=0; f1<last; f1++) {
        new_arr[f1] = array[f1];
    }
    this->size = new_size;
    delete[] array; //free memory
    array = new_arr;
}

1 Comment

Thanks, your answer is so simple

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.