Delete a dynamic array but keep a pointer

旧巷老猫 提交于 2021-02-08 06:34:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!