Archived

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

Xiachunyi

C++: Deleting a dynamic struct

Recommended Posts

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;
        double fade;
        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].fade=1.0;
           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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
You could also use enums -

enum DamageType{wind, water, fire, lightning};

Then you can refer to it by either its name or number - the first element starts from 0...n-1. So ''wind'' in my example would be 0, ''water'' 1, and so on. I find it more convenient because it saves space, is easy to understand and groups elements of the same type under one title - promotes object orientation.

Share this post


Link to post
Share on other sites