问题
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:
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.
回答2:
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;
}
来源:https://stackoverflow.com/questions/13415572/delete-a-dynamic-array-but-keep-a-pointer