Creating pointer array using "new"...

This topic is 4624 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Let's say I've created a class to hold information about enemies and I want to dynamically create an array to keep track of their state. This array is going to be incorporated into an "Enemy Manager" class. I know that traditionally, an array's size is set at compile time, but this can be walked around by allocating the memory dynamically, so I'm using the new keyword. So... How would I do it? My initial thought was the following:
class EnemyManager{

public:
EnemyManager(int size)
{
tracker = new *Enemy[size];
}

private:
Enemy **tracker;
}

For some reason, this does not compile. It complains that the * in front of the work Enemy in the constructor is a syntax error. What am I missing? And yes, I could proably be using vectors or some other data structure, but I just thought this way would provide certain advantages. Besides, I want to know WHY it's wrong. :P

Share on other sites
Change new *Enemy[size] to new Enemy*[size].

Share on other sites
As would be stated in the vernacular: "j00 roxxorz" :D

Thanks for the info.

Share on other sites
OTOH, since you are using C++, this solution might be better:

class EnemyManager{  public:     EnemyManager(int size)     {       if (size < mTracker.size())       {         // clear the Enemy* from size to mTracker.size()       }       // then resize...       mTracker.resize(size);     }  private:     std::vector<Enemy*> mTracker;}

(EDIT)
Fortunately, snk_kid just show me that I was somewhat stupid (he didn't say that, of course [wink]). Since I am in a constructor, the code is oversimplified to a simple
class EnemyManager{  public:     EnemyManager(int size) : mTracker(size)     {     }  private:     std::vector<Enemy*> mTracker;}

Apologies for the previous post - and big thanks to snk_kid (yu are allowed to rate him up).

Regards,

[Edited by - Emmanuel Deloget on June 23, 2005 12:39:23 PM]

Share on other sites
Quote:
 Original post by TheWandererBesides, I want to know WHY it's wrong. :P

The syntax for a new array allocation is new type[size]. In your case, you want an array of "pointer to Enemy", which is written Enemy*, not *Enemy.