trying to figure out this array double but I keep getting a
trying to figure out this array double, but I keep getting a bunch of random numbers. I get the correct number of outputs, but the outputs are garbage.
Write a C++ function to double the size of an array an arbitrary number of times. The function takes three arguments the initial 1D array, its size, and the number of times to double it. The function should dynamically create the new array to be 2x the size of the array argument, copy the contents into the new array, and for the second half of the array, create new values by doing 2 the values in the first half of the array, then delete the original array. Repeat this process for the specified number of times, then return the new array. int Array DynamicAllocation (int arrayO, int size, int number) Helpful Hints: For an input array argument with a size of 2, you should create the array and double it which gives an array of: NULL NULL NULL NULL to double an array: int newArray new int 12 size], //using a loop: for i 0 to size-1) //copy the current array to the new array which give an array of: 0 1 NULL NULL //copy first half of new array to second half which gives an array of: 0 1 0 1 //second half 2 old values which gives an array of: 0 1 0 2 //and follow the remaining directions. For example: Test Result int arr 21 10, 1); 0 1 0 2 0 2 0 4 0 2 0 4 0 4 0 8 array size 2; number 3;Solution
Here is the code for you:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//You should have a utility function that takes an array and its size as input and prints the contents of the array.
void printArray(int *array, int size)
{
for(int i = 0; i < size; i++)
cout<<array[i]<<\" \";
cout<<endl;
}
//A function that accepts an int array and the array\'s size as arguments.
//The function should create a new array that is twice the size of the argument array.
//The function should then copy the contents of the argument array to the new array and
//unused elements of the new array should be set to zero.
//The function should return the new array.
int* ArrayDynamicAllocation(int array[], int size, int number)
{
for(int l = 0; l < number; l++)
{
int* newArray = new int(size * 2);
for(int i = 0; i < size; i++)
*(newArray+i) = *(array+i);
int j = 0;
for(int i = size; i < 2*size; i++)
{
*(newArray+i) = *(array+j) * 2;
j++;
}
delete array;
array = newArray;
size *= 2;
//printArray(array, size);
}
return array;
}
int main()
{
/*int *array = (int *)malloc(sizeof(int) * 2);
*array = 2;
*(array + 1) = 4;*/
int *arr = new int(2);
*arr = 0;
*(arr + 1) = 1;
int array_size = 2;
int number = 3;
arr = ArrayDynamicAllocation(arr, array_size, number);
printArray(arr, 16);
cout<<endl;
}

