Hi!
I have been reading about how important it is to use the delete operator to avoid memory problems. However, I was wondering if it is possible to remove a pointer.
For example, imagine that I created a class cow. Imagine that I am using an array of pointers which point to objects of class cows (to all my 7 cows):
|
|*cow0|*cow1|*cow2|*cow3|*cow4|*cow5|*cow6|
|
if cow2 dies, I'd like to delete the object cow2 and move the subsequent pointers one position to the left. I'd use this code:
1 2 3 4 5 6
|
length_array--;
dead=2;
delete array_cows[dead];
for(int i=dead;i<length_array;i++){
array_cows[i]=array_cows[i+1];
}
|
After that, what I would have is:
|
|*cow0|*cow1|*cow3|*cow4|*cow5|*cow6|*cow6|
|
So, 2 questions which are somehow related:
1st - I don't want the cow6 to be replicated at the end. How could I delete that? Maybe doing:
1 2 3 4 5
|
array_cows[length_array] = null;
//or
array_cows[length_array]=0xcdcdcdcd;
|
???
2nd - the object cow2 was deleted but the pointer *cow2 is not deleted and it still exists (pointing to nowhere). How could I also delete it since I don't use it anymore and it is wasting memory(very little, I guess)?
Thank you in advanced