调整任何动态数组大小的函数 [英] A function to resize any dynamic array
问题描述
我正在尝试实现一个函数,该函数可以将任何数据类型的动态数组的大小增加一个,使该数组保留所有现有数据。
I'm trying to implement a function that can increase the size of a dynamic array of any data type by one, having the array keep all of it's existing data.
我想这样做是因为我们经常需要在课堂上为实际项目使用动态数组并调整其大小,因此,根据我的意愿,我不能使用向量。
I want to do this since we regularly need to use and resize dynamic arrays for practical projects in class, so as much as I would like to, I can't use vectors.
我首先想知道是否可以这样做,如果可以的话,是否有人可以告诉我如何做。
I would firstly like to know if this can be done, and if so, if someone could show me how.
这是我到目前为止所掌握的。
This is what I have so far.
template <typename Temp>
void incArraySize(Temp * dynamicArray, int i_Elements)
{
Temp * dummyArr = new Temp [i_Elements];
for (int l = 0; l < i_Elements; l++)
dummyArr[l] = dynamicArray[l];
delete [] dynamicArray;
dynamicArray = new Temp [i_Elements+1];
for (int l = 0; l < i_Elements; l++)
dynamicArray[l] = dummyArr[l];
delete [] dummyArr;
}
在第一次调用该函数时效果很好,但是我可以访问
This works fine the first time the function is called, but I get an access violation for subsequent times.
推荐答案
dynamicArray
应该通过引用传递,
dynamicArray
should be passed by reference,
void incArraySize(Temp*& dynamicArray, int i_Elements)
否则, dynamicArray = new Temp [i_Elements + 1];
行中的重新绑定
即调用时
int* array = new int[10];
incArraySize(array, 10);
// line 3:
std::cout << array[0];
在第3行,该数组已由 incArraySize <删除[] ed / code>,但是
array
变量仍指向此旧的,已删除的数组。这就是为什么您遇到访问冲突。
at line 3, the array has been delete[]ed by incArraySize
, but the array
variable is still pointing to this old, deleted, array. This is why you get the access violation.
您是否考虑过 std :: vector< Temp> ;
代替?标准库类型可以为您正确管理内存和大小,并且更易于使用。
Have you considered std::vector<Temp>
instead? The standard library type can manage the memory and size correctly for you and is much easier to use.
这篇关于调整任何动态数组大小的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!