Reputation: 1863
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;
Upvotes: 0
Views: 583
Reputation: 782488
The access loop should be:
for (int i = 0; creatures[i] != NULL; i++) {
Creature *creature = creatures[i];
creature->travel();
}
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:
for (Creature **creature = &creatures[0]; *c != NULL; c++) {
(*creature)->travel();
}
Upvotes: 1
Reputation: 73587
Your creature
is a pointer to a Creature
. If you increment this pointer, you will point to the next Creature
behind the currently pointed one and not to the next pointer in your table.
Use:
for (int i=0; creatures[i]!=nullptr; i++) {
creatures[i]->travel();
}
Upvotes: 2