I have a PiggyBank class that stores "Coins" with the functions DropIn and GrabOut. The functions will store a pointer to the "Coins" in an growable array of pointers. (coinStorage**) The functions look like this:
DropIn is passed the array address, size, and a pointer to the coin that is supposed to be "Dropped In".
GrabOut is passed the array address and size, makes a copy of the passed array of pointers with size-1, and returns the Coin* that was "removed" from the array.Code:bool PiggyBank::DropIn(Coin** coinStorage, int& size, Coin* coin) { Coin** temp = 0; temp = new Coin* [size+1]; if(!temp) return false; for(int x=0; x<size; x++) temp[x] = coinStorage[x]; temp[size] = coin; size++; if(coinStorage) delete [] coinStorage; coinStorage = temp; return true; }
My problem is that it appears as though the functions are not actually changing coinStorage "out of scope", because when I call DropIn() twice, on the second call, I assumed that the value from the first call should be in coinStorage[0], but it is not. What am I missing here?Code:Coin* PiggyBank::GrabOut(Coin** coinStorage, int& size) { if(size) { Coin* save = coinStorage[size-1]; Coin** temp = new Coin* [size-1]; for(int x=0; x<size-1; x++) temp[x] = coinStorage[x]; size--; if(coinStorage) delete [] coinStorage; coinStorage = temp; return save; } else { cerr << "GrabOut(): No coins to grab!\n"; return 0; } }
One solution was for me to modify DropIn() to return temp** instead of a bool, and have the storage = the returned ** outside of the function.. but I'm still curious why my original method didn't work.
I do realize I could use std::vector, but this is an exercise, and we are supposed to create our own growable array.
Thanks in advance for any help!



LinkBack URL
About LinkBacks



