Jump to content


Object array comparison.


2 replies to this topic

#1 Wade Berkn

    New Member

  • Members
  • PipPip
  • 14 posts

Posted 31 May 2007 - 02:17 AM

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.

#2 Reedbeta

    DevMaster Staff

  • Administrators
  • 4780 posts
  • LocationBellevue, WA

Posted 31 May 2007 - 06:13 AM

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++.
reedbeta.com - developer blog, OpenGL demos, and other projects

#3 Wade Berkn

    New Member

  • Members
  • PipPip
  • 14 posts

Posted 31 May 2007 - 08:48 AM

Thanks alot, that was alot of help!





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users