问题
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.
回答1:
dynamicArray should be passed by reference,
void incArraySize(Temp*& dynamicArray, int i_Elements)
otherwise the rebinding in the line dynamicArray = new Temp [i_Elements+1]; will not be applied outside of the function.
That is, when you call
int* array = new int[10];
incArraySize(array, 10);
// line 3:
std::cout << array[0];
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.
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.
回答2:
Increasing the size of the array by one will be incredibly inefficient especially if you need to do this multiple times. I would suggest sacrificing some memory and using more space than you need, or using a list where you can use a .push() method
In your current method it looks like you are copying pointers to the new array as opposed to copying the individual values from dummy array to dynamic array, try using the new keyword inside the for loop to make sure that you pass the data each time you copy it over
回答3:
Why two copies? And as KennyTM noted you need a reference:
template <typename Temp>
void incArraySize(Temp *& dynamicArray, int i_Elements)
{
Temp * p = new Temp[i_Elements + 1];
for (int l = 0; l < i_Elements; l++)
p[l] = dynamicArray[l];
delete [] dynamicArray;
dynamicArray = p;
}
来源:https://stackoverflow.com/questions/17200649/a-function-to-resize-any-dynamic-array