I've been trying to resize this array, and it compiles just fine, but when I run it I get this really long error message.
Here's the code for the function:
void arrayClass_Namespace::arrayClass::resize(int newSize)
{
std::cout << "\nPlease input a new size for the array: ";
std::cin >> newSize;
assert(newSize < MAX_SIZE);
int *resize_arr = new int[newSize];
for(int index = 0; index < size; index++)
{
resize_arr[index] = arr[index];
}
size++;
arr = resize_arr;
delete[] resize_arr;
}
Here's the updated code that works perfectly fine now:
void arrayTools_GabriellaRamirez::arrayTools::resize(int newSize)
{
std::cout << "\nPlease input a new size for the array: ";
std::cin >> newSize;
assert(newSize < MAX_SIZE);
int *resize_arr = new int[newSize];
for(int index = 0; index < size; index++)
{
resize_arr[index] = arr[index];
}
for(int index = size; size < newSize; index++)
{
size++;
}
for(int index = size; size > newSize; index++)
{
size--;
}
delete [] arr;
arr = resize_arr;
}
delete[] resize_arr
is deleting the new array you made. You need to do
delete[] arr;
arr = resize_arr;
As an aside, you don't check to make sure the new array size is not smaller than used
so you could potentially write out of bounds of the new array.
Also I think size++
is not correct.