Click here if you are stuck in someone else's frames.

If this page looks like garbage then you need one of these browsers...

Microsoft Internet Explorer

Netscape Navigator

Please sign my programmer's page guestbook.

Please sign my guestbook

View my guestbook entries

We build it up, we must also tear it down.

Just as we wrote a function that builds the frames array (image array) and do some initialization, we must also write a function that tears down the images so we could safely delete our sprite. Otherwise, our programs will leak memory by losing pointers. In contrast with initialization, destroying sprites are not nearly as complex. Let's take a look at the code.

void DestroySprite(struct Sprite *thisSpr)
{
    int i;

    if (thisSpr->background != NULL)
        farfree(thisSpr->background);

    if (thisSpr->frames != NULL) {
        for (i=0; i<thisSpr->noOfFrames; i++)
            if (thisSpr->imgDynamic && thisSpr->frames[i] != NULL)
                farfree(thisSpr->frames[i]);
        free(thisSpr->frames);
    }
}
    

There you go, pretty simple huh? Compared to building it at least. Then again, it's always easier to destroy anything than it is to build it, right? Let's disect this function though to see what it is doing.


The first if statement checks to see if the background has a pointer assignment other than NULL. If so, the function will free the memory that has been allocated. The second if statement checks for a frames array (of far pointers), if it has one then it will cycle through every far pointer (using the for loop) checking for a valid pointer and whether or not it is expecting dynamic images. If both conditions are true, it will free each far pointer. After it finishes with freeing the far pointers, it will then free the frames array itself (the last free statement).

Note: Be careful not to directly assign anything to these pointers (frames, frames[] and background) outside of our functions. The functions we write will assume that all of the memory has been allocate for every pointer that is not equal to NULL. Freeing memory to a pointer that memory was not allocated to in the first place can crash the system. So unless you know what you are doing, avoid direct assignments of these pointers outside of the functions that we intend to write for the sprites.

Okay, that was interesting, now what else do we plan to do with sprites. Well, uh, how about writing functions that can draw them on the screen. Sprites are pretty useless unless we had some way to show there images and move them around on the screen.


Send your questions, comments, or ideas to: wilkeg@gamewood.net

This page hosted by GeoCities Get your own Free Home Page
 Next Back |