I am having trouble dynamically resizing an array in one of my C++ classes.
I am specifically having trouble inside the setCoefficient
function of my code, where I need to resize a dynamic array. Currently, I am running into an error of HEAP CORRUPTION DETECTED
when I try and delete the old dynamic array in the setCoefficient
function.
I have commented the setCoefficient
function and was hoping someone could go through and help me determine where I am going wrong.
void Poly::setCoefficient(const int coefficient, const int power) {
if (power > this->length) {
//we need to resize the array we currently have.
//Here I am creating a new array that will temporarily store larger values
int* resizedArray = new int[power * 2];
//This for loop assigns all the values in the current object's array to the new array (resizedArray)
for (int i = 0; i < this->length; i++) {
resizedArray[i] = this->polyArray[i];
}
//Here I am adding the term that we wanted to add in the first place with setCoefficient
resizedArray[power] = coefficient;
//Deleting the terms in polyArray
delete [] this->polyArray;
//Creating a new array that has been resized
this->polyArray = new int[power * 2];
//Setting the values of the temporary array, resizedArray, to the array of the current object.
this->polyArray = resizedArray;
//modifying the length of the current object.
this->length = power * 2;
}
else {
this->polyArray[power] = coefficient;
}
}