删除动态数组但保留指针 [英] Delete a dynamic array but keep a pointer
本文介绍了删除动态数组但保留指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我做了一个扩展数组的函数,这个函数在一个类里面.
I have made a function for expanding array, and this function is inside a class.
因为此函数创建 new_arr
并将所有 array
的数字复制到 new_arr
中,最后设置 array的指针
和 new_arr
,我很想知道如何删除 array
中的数字,因为我不再需要
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;
}
谢谢
推荐答案
假设这是一种练习,请先删除数组,然后再重新分配给新数组:
Assuming this is an exercise, then delete the array before re-assigning to the new one:
delete [] array;
array = new_arr;
在实际代码中,请使用 std :: vector< int>
而不是动态分配的数组.
In real code, use an std::vector<int>
instead of the dynamically allocated array.
这篇关于删除动态数组但保留指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文