I have been working on a function that accepts an array and an array size as an argument. The functions task is to create a second array that is twice the size of the fist array, copying the elements of the first array into the first half of the second array, and initializing the remaining elements to zero.
I can only get this to work if I dynamically allocate the second array with in the function. I suspect this is because once a function returns control to the calling function, any array that is not dynamically allocated is deleted from memory. In other words, the pointer in the calling function will point to junk data because the second array that was created in the expander function is now gone. Can anyone confirm this?
Here is the function written two different ways.
This way works
int *array_expander(int array[], int size)
{
int *new_array = new int[size*2];
for(int i{0}; i < size; i++)
*(new_array + i) = *(array + i);
for(int i{size}; i < size * 2; i++)
*(new_array + i) = 0;
return new_array;
}
This way doesn't
int *array_expander(int array[], int size)
{
int new_array[size * 2];
for(int i{0}; i < size; i++)
*(new_array + i) = *(array + i);
for(int i{size}; i < size * 2; i++)
*(new_array + i) = 0;
int *arr_ptr = new_array;
return new_array;
}