0
Asteroid* rocks[maxAsteroids] = {};

So Asteroids is a pointer to a class, at least thats how I understand it. My question is I can't have maxAsteroids be a const, and I know it can't be a simple variable. So what is the proper way to initialize a variable size to a pointer array? This feels like a misunderstanding on my part of syntax, but I'm just not getting it. Appreciated!

5
  • 1
    Use dynamic allocation. "On the stack" vanilla arrays cannot be resized and their size must be known at compile time. Or better off use some container class. Commented Mar 14, 2014 at 0:58
  • 1
    Why not use a vector or some other collection? Commented Mar 14, 2014 at 0:58
  • 1
    possible duplicate of C++ Initialize array pointer Commented Mar 14, 2014 at 0:58
  • is there an explanation of vector you guys can point (get it?) me to? I saw that around but nothing I read seemed to clear that up. Commented Mar 14, 2014 at 1:04
  • 1
    "Asteroids" isn't even in your code, let alone being a "pointer to a class". rocks is an array. Each member of that array is a pointer that can point to an object of type Asteroid, although it is currently a null pointer. Commented Mar 14, 2014 at 1:08

1 Answer 1

2
std::vector<Asteroid*> roids;
roids.resize(maxAsteroids);
Sign up to request clarification or add additional context in comments.

12 Comments

Thanks that is the answer I needed, though I'll need to look into understanding the vector portion of it, the resize really would have helped to have known about before. Anyway thanks for being so fast.
the STL is your friend. This site is also your friend.
@MattMcNabb - reserving doesn't help you much when you need to reorder objects from and to arbitrary positions. And as you become more experienced at programming, you will realize that putting pointers to objects into containers is much more common than putting actual objects. Not only does it offer tremendous advantage as a single object available in multiple different containers at the same time, but sometimes objects are required to have unique identities, making it impossible to move the actual object to another container, you can only use pointers. Dont be arrogant pay attention and learn
Thanks for all the advice and comments, as always very helpful community.
I've been a professional programmer for 16 years and my experience is that the simplest solution is the easiest one to both write and maintain. So far OP has said nothing to indicate that adding an extra layer of indirection is necessary for his project.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.