Sign in to follow this  
TheWanderer

Creating pointer array using "new"...

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 this post


Link to post
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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this