So i've been able to learn to expand an array, but was wondering how i would go about adding elements to the expanded space, here is what i have so far.
int *expand(int *arr, int size)
{
int *newArray;
newArray = new int[size * 2];
memcpy( newArray, arr, size * sizeof(int));
for (int index = 5; index < size; index++)
new开发者_如何学JAVAArray[index] = 0;
return newArray;
}
I think you might have a bug in your code. newArray is of size "size * 2", but you initialize elements only up until "size".
Try this:
newArray = new int[size * 2];
memcpy( newArray, arr, size * sizeof(int));
for (int index = size; index < (size*2); index++)
newArray[index] = 0;
return newArray;
This should initialize all the elements in the new space to 0's.
精彩评论