I am trying to create a null terminated array of objects like this
void Game::createCreatures(int numCreatures) {
creatures = new Creature *[numCreatures + 1];
for (int i = 0; i <= numCreatures; i++) {
if(i < numCreatures) {
creatures[i] = new Runner(maze);
} else creatures[i] = NULL;
}
}
Then access them like this
for (Creature *creature = creatures[0]; creature != NULL; creature++) {
creature->travel();
}
What exactly am I doing wrong? I am receiving a EXC_BAD_ACCESS when I attempt to 'travel' the creature. I know there is something wrong with the creation of the array because if I attempt to print the address of all of the creatures using my accessing for loop, it prints forever. I know there is something wrong with my pointer logic, help?
creatures declaration is this
Creature **creatures;
The access loop should be:
Your loop is treating
creatures[0]
as an array of creatures, but it's just a single creature.If you want to do the loop with pointer arithmetic, it should be: