XianForce wrote:Amarant wrote:...
One thing... Won't this just make it so TWO elements in the array have the same value?, I think you need to do something like:
Code: Select all
void RemoveShip(int index)
{
delete battleships[index];
battleship_count--;
battleships[index] = battleships[battleship_count];
battleships[battleship_count = NULL;
}
Right?
Oh and because your incrementing battleship_count for each ship you add, you'll have an 'off by one error' won't you? Because battleship_count is how many battleships you have, but the last battleship in the array would be battleship_count - 1, wouldn't it?
Hmmm, I do think my version was correct. Let me think it through.
When you call RemoveShip battleship_count will equal the amount of elements in the array.
So if you use that count as an index, it will point to exactly one position after the last element.
If you then decrement that count, it will point exactly to the last element.
Using it now as an index will get you the last element.
Then assign that last element to the position in the array you've just emptied.
This will indeed result in there being two identical pointers in the array.
But remember that the battleship_count was decremented.
So the next time you will use the add function it will simply be overwritten.
I intentionally named the variable battleship_count, indicating that it is the count of battleships in the array.
If I would have wanted to store the highest index in the array I would have chosen another name for the variable.