Creating pointer array using "new"...

Started by
3 comments, last by Zahlman 18 years, 10 months ago
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
Advertisement
Change new *Enemy[size] to new Enemy*[size].
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other player's eyes with his King.
As would be stated in the vernacular: "j00 roxxorz" :D

Thanks for the info.
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]
Quote:Original post by TheWanderer
Besides, 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.

This topic is closed to new replies.

Advertisement