PDA

View Full Version : Object array comparison.


Wade Berkn
05-30-2007, 07:17 PM
Im kinda new to C++ but I've worked with C and Java, what Im trying to do is create an object array to hold "bullet" objects.
I've used the C malloc call to allocate enough memory for 10 bullets with this call: Bullet* bulletArray = (Bullet*) malloc(10*sizeof(Bullet));

Now I want to be able to add bullet objects to that array whenever the player presses fire, but Im not sure how to check if a spot in the array is NULL, i thought it was fine just to say bulletArray[x]==NULL or '\0' because I thought arrays in themselves were pointers, thanks for any help guys.

Reedbeta
05-30-2007, 11:13 PM
First of all, in C++ you should use new and delete instead of malloc.

Bullet *bulletArray = new Bullet[10];
// later on...
delete[] bulletArray;

Second, while the array itself can be used like a pointer in many situations, the elements of the array are not themselves pointers, they are actual objects. You could have a flag in the Bullet object that says whether it is currently active or not, so you could loop through the array to find an inactive bullet when creating a new one.

Alternatively, you could actually create an array of pointers:

// create an array of pointers to bullets
Bullet **bulletPtrArray = new Bullet*[10];
// create a single bullet and make one array element point to it
bulletPtrArray[5] = new Bullet;
// later on, delete that bullet and reset the pointer to null
delete bulletPtrArray[5];
bulletPtrArray[5] = NULL;
// later on, delete the array of pointers (make sure you've deleted all the bullets first, as they are NOT automatically deleted)
delete[] bulletPtrArray;
Note the 'delete' for deleting individual objects and 'delete[]' for deleting arrays.

C++ also provides a built in classes called std::vector and std::list, which represent dynamically-resizeable arrays and linked lists respectively. These are part of what is called the STL (standard template library) and are often easier to use than C arrays. But you'll learn about these as you gain more knowledge of C++.

Wade Berkn
05-31-2007, 01:48 AM
Thanks alot, that was alot of help!