c++ null terminated array of objects

591 views Asked by At

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;
2

There are 2 answers

5
Barmar On BEST ANSWER

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();
}
0
Christophe On

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();
    }