Dynamic Array Issue
Mar 5, 2013 at 7:18pm Mar 5, 2013 at 7:18pm UTC
I've written functions to increase, and decrease, my array. It works fine when increasing, however, when I go to shrink it, it crashes :(
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
void Register::GrowArray()//Similar to class provided code
{
static Sale* temp;
temp = new Sale[MaxArray+ARRAYSIZE];
for (int i = 0; i < MaxArray; i++)//Copies Data
temp[i] = saleArray[i];
delete [] saleArray;
saleArray = temp;
cout << "Increased register size to: " << MaxArray+ARRAYSIZE << endl;
}
void Register::ShrinkArray()
{
static Sale* temp;
temp = new Sale[MaxArray-ARRAYSIZE];
for (int i = 0; i < MaxArray; i++)//Copies Data
temp[i]= saleArray[i];
delete [] saleArray;
saleArray = temp;
cout << "Decreased register size to: " << MaxArray-ARRAYSIZE << endl;
}
Does anyone have any Idea what may be wrong?
Mar 5, 2013 at 7:25pm Mar 5, 2013 at 7:25pm UTC
I'm gonna assume it has to do with temp = new Sale[MaxArray-ARRAYSIZE];
What is MaxArray and what is ARRAYSIZE?
Mar 5, 2013 at 7:27pm Mar 5, 2013 at 7:27pm UTC
In your for loop in the ShrinkArray() method, i is increasing to 'MaxArray' where your temp array only has 'MaxArray - ARRAYSIZE' size. So you are attempting to access out of bounds of temp when you do:
So just change your for loop to:
1 2
for (int i = 0; i < MaxArray - ARRAYSIZE; i++)//Copies Data
temp[i]= saleArray[i];
Topic archived. No new replies allowed.