#### Archived

This topic is now archived and is closed to further replies.

# C++: Deleting a dynamic struct

## Recommended Posts

Xiachunyi    556
Hello I am wondering if I am deallocating memory correctly by the following code: Is this the way to delete allocated memory for a structure or will I have to loop through each instance of the structure allocated?
...
if(mode == 0 || mode == 4)
{
delete [] fall;
fall=NULL;
}
...

Here is my structure and the allocation routine
...
unsigned int updown_objects=100;
typedef struct
{
double size;
double x_pos;
double y_pos;
double speed_fall;
double red;
double green;
double blue;
int exchange;
bool start_assign;
}
falldown_struct;
falldown_struct *fall;
int change_sign=0;
...
if(mode == 0 || mode == 4)
{
updown_objects=quantity;
fall=new falldown_struct[updown_objects];
if(fall == NULL)
{
MessageBox(GetActiveWindow(),"Particle Generator: \"Falldown\"", error_title[0],MB_ICONERROR);
return FALSE;
}
for(loop=0; loop < updown_objects; loop++)
{
fall[loop].size=rand()%100*size;
fall[loop].x_pos=0.0;
fall[loop].y_pos=0.0;
fall[loop].speed_fall=rand()%100*speed_edit;
do
{
fall[loop].speed_fall=rand()%100*speed_edit;
}while(fall[loop].speed_fall < 9*speed_edit);
fall[loop].red=rand()%100*.01;
fall[loop].green=rand()%100*.01;
fall[loop].blue=rand()%100*.01;
fall[loop].exchange=1;
}
change_sign=0;
}
...

The reason I am asking this is because if I allocate memory utilizing the same routine after deleting an allocation containing more members then there are some "foreign" values in my particle generator''s variable that aren''t suppose to be there. If my de-allocation is alright then it is probably my generator. Thank you.

##### Share on other sites
evolutional    1393
I thought you could call a delete [] to remove them all

##### Share on other sites
Zahlman    1682
delete[] is fine.

Good god, please do something about that ''mode'' value. At least make some constants for the different modes instead of magic numbers.

##### Share on other sites
Xiachunyi    556
Okay, thank you.

quote:

Good god, please do something about that ''mode'' value. At least make some constants for the different modes instead of magic numbers.

Do you define the numbers as a constant name? Like this:
#define UPDOWN  4#define FIRE    5

and so on?

##### Share on other sites
UberGeek    138
Yes, or use:

const int FIRE = 5;

if you want to avoid the use of the preprocessor.

##### Share on other sites
Xiachunyi    556
Thank you I''ll change it to that right away - makes it more understandable.