James2250 suggestion makes sense if you intend to use a fixed size grid; far safer than dynamic memory. And in real code you'd use std::vector or equivalent, as mutexe mentioned, if you required a variable sized grid.
But if you're doing this as an exercise on using pointers, etc...
organisms[15]= .....? I am stuck here
As you are using polymorphism I presume...
It has an Organism class, an ant class and a bug class. Organism is parent. Other two inherits from parent. |
... you need your grid to store base class (Organism*) pointers rather than Organisms. So you need to use an extra *:
1 2 3 4 5 6
|
// create an array of Organism**s
Organism*** organisms = new Organism**[20](); // use value initialization
// for each element of this array create a child array of Organism*s
for(int i=0;i<20;i++)
organisms[i] = new Organism*[20](); // // use value initialization
|
so you end up with a "grid" of Organism* elements (not Organism instances like you had.)
The () after the [] used when new-ing the arrays tells the compiler to value initialize them (to fill them with zeros.) Without it the arrays would all be filled with whatever happens to be in the memory the allocator gives you (or sometimes a debug fill pattern, if you're using a debug allocator.)
In C++11 you can use {} rather than (), which is all C++03 understands.
(Aside: you can do the same for an array:
Organism *organisms[20][20] = {0}; // also works in C
Organism *organisms[20][20] = {}; // works in C++
)
or
Organism *organisms[20][20]{}; // works since C++11
And if an array -- or a normal variable -- is global or static then it's automatically zeroed anyway.)
You can then access them in the same ways as James2250's array based example.
organisms[15][12] = new Ant;
operator[] acting on organisms returns the Organism** for the row.
operator[] acting on the returned Organism** returns the Organism* pointing at the instance.
Of course, you've to free all the memory you allocated above!
Andy
PS Please use code tags!
Also see the article "How to use code tags"
http://www.cplusplus.com/articles/jEywvCM9/