0

我正在尝试创建一个像这样的以空结尾的对象数组

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

然后像这样访问它们

for (Creature *creature = creatures[0]; creature != NULL; creature++) {
    creature->travel();
}

我到底做错了什么?当我尝试“旅行”该生物时,我收到了 EXC_BAD_ACCESS。我知道数组的创建有问题,因为如果我尝试使用我的访问 for 循环打印所有生物的地址,它会永远打印。我知道我的指针逻辑有问题,帮助?

生物宣言是这个

Creature **creatures;
4

2 回答 2

2

creature是指向 a 的指针Creature。如果你增加这个指针,你将指向Creature当前指向的指针后面的下一个,而不是表中的下一个指针。

利用:

for (int i=0; creatures[i]!=nullptr; i++) {
        creatures[i]->travel();
    }
于 2014-11-15T00:42:39.943 回答
1

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();
}
于 2014-11-15T00:42:39.717 回答