问题
I am programming with the C++ Builder from Embarcadero.I created an TImage Array :
TImage *Image[c] ; // c is 5
after that I am creating dynamic Images on an BUTTON CLICK :
for (int i = 0; i < c; i++)
{
Image[i] = new TImage(this);
Image[i]->Parent = BoardItem ; // BoardItem is an Item of an TabControl
Image[i]->Height = 20 ;
Image[i]->Width = 20 ;
Image[i]->Position->X = d ; // d and e are defined in the public var's.
Image[i]->Position->Y = e ;
Image[i]->Bitmap = Icon->Bitmap ; // Icon is an Image on my Formular
}
It's working fine but the Icon->Bitmap is from a Database , which is also working fine . But on an second Button Click the old Images are not deleted. So everytime when I'm clicking the button again, the program is creating 5 more Images but the old ones are still there.
My question is now, how to refresh the old Images ? Should i delete the old Images an create then the new Images ? ( I tried this with ( delete , Free () , delete[] Array, but im always getting a violence ERROR ) Or should i refresh the old Images, in case there are Updates on the Bitmaps of the Images in the Database, and how ?
回答1:
You need two things:
Make sure that the pointers are initialized to null the first time around:
TImage* Image[c] = {};Delete the old image when you load a new one:
delete Image[i]; Image[i] = new TImage(this);
Note that using delete on a null pointer is perfectly safe; it just doesn't do anything. So nothing changes on the first set of images, and each subsequent set automatically clears out the old ones instead of leaking.
回答2:
@Ben Voigt here you got my whole Code hope you can understand it . Everytime i want to click the button the old images should be refreshed. To do that i want to delete the old an after that crate the new ones .
TImage *Image[20]= {} ;
for (int i = 0; i < c; i++)
{
str = " Hallo "
Image[i] = new TImage(this);
Image[i]->Parent = BoardItem ;
Image[i]->Height = 20 ;
Image[i]->Width = 20 ;
Image[i]->Position->X = d ;
Image[i]->Position->Y = e ;
Image[i]->Bitmap = Icon->Bitmap ;
Image[i]->StyleName = str ;
Image[i]->OnClick = ImageClick ;
d = d + 20 ; // the next Image should be x-Position +20
if (d == 367) { // 367 is the Width of my Formular
d = 7 ; // If it is 367 Position-x is 7 again und Position-y is +20
e = e + 20 ;
}
}
来源:https://stackoverflow.com/questions/34665307/c-delete-objects-of-dynamic-array