I am passing a dynamic array to a function with a value that is meant to be added to the array and when I enlarge and reset the array dynamically and iterate over the array I find the last value of the array is a garbage value rather than what is expected. I've looked at a few other posts on SO as well as some documentation and i'm stumped on what i'm doing wrong. I would prefer to use a vector, but my assignment requires a dynamic array unfortunately. Any thoughts? Thanks.
Post above is passing pointers to vectors by reference and has nothing to do with enlarging dynamic arrays
Main
cout << "Please enter the size of the array of integers you would like to create: ";
cin >> size;
cout << "\nPlease enter your integers:\n";
int *integerArray = new int[size];
//store values in array
for (int dynamicArrayDataCounter = 0; dynamicArrayDataCounter < size; dynamicArrayDataCounter++)
cin >> integerArray[dynamicArrayDataCounter];
cout << "\n Please enter the integer you would like to insert into this array: ";
cin >> userInt;
InsertIntegerToSortedList(integerArray, userInt, size);
//Print array for proof
for (int counterPrinter = 0; counterPrinter < size + 1; counterPrinter++)
cout << endl << integerArray[counterPrinter];
//Remove memory and repoint dangling pointer
delete [] integerArray;
integerArray = NULL;
return 0;
}
Function
void InsertIntegerToSortedList(int *integerArray, int userInteger, int size)
{
//Declare new array to add index position for integerArray
int *resizedArray = new int[size + 1];
bool numInserted = false;
for (int counter = 0; counter < size + 1; counter++)
{
if (integerArray[counter] < userInteger)
{
resizedArray[counter] = integerArray[counter];
}
else if ((integerArray[counter] > userInteger && integerArray[counter - 1] < userInteger) || integerArray[counter] == userInteger || (integerArray[counter] <= userInteger && size - counter == 1))
{
resizedArray[counter] = userInteger;
numInserted = true;
}
else if (numInserted)
resizedArray[counter] = integerArray[counter - 1];
}
//Store resizedArray values in integerArray
integerArray = resizedArray;
//Remove dynamic array on heap and repoint dangling pointer
delete[] resizedArray;
resizedArray = NULL;
}