#include<iostream>
int *addElementToArray(int *arr, int currSize);
int main()
{
int arraySize = 2;
int *arr = newint[arraySize];
int currentIndex = 0;
int value;
std::cout << "Type 0 to exit or any other number to continue\n";
std::cin >> value;
while(value != 0)
{
if(currentIndex == arraySize)
{
addElementToArray(arr, arraySize);
arraySize++;
std::cout << "Had to add another element to the array!\n";
}
arr[currentIndex] = value;
currentIndex++;
std::cout << "Type another value or 0 to exit\n";
std::cin >> value;
}
for(int i = 0; i < arraySize; i++)
{
std::cout << arr[i] << "\n";
}
return 0;
}
int *addElementToArray(int *arr, int currSize)
{
int *newArr = newint[currSize + 1];
for(int i = 0; i < currSize; i++)
{
newArr[i] = arr[i];
}
delete arr;
return newArr;
}
The original code has a significant error.
At line 17: addElementToArray(arr, arraySize);
This should actually read: arr = addElementToArray(arr, arraySize);
Without that, the newly-allocated array is never used, instead values continue to be added to the now deleted old array.
As well as the already mentioned line 40 delete [] arr;
Also, less important, but good practice, just before the end of main(), the array arr should be deleted too. That way, each new [] will be paired with a matching delete []
Rather than returning a pointer to the new array, function addElementToArray returns the new size of the array. Also, rather than increasing the array size by 1 each time, different strategies can be employed, such as adding 10 or 100 elements. This version increases the array size by 50% each time. For large quantities of data, this is much more efficient in terms of the number of re-allocations and copying of elements.
I tested this using a data file rather than keyboard input, it was just a list of prime numbers but any file of integers would do.