尽管被直接设置,指针数组仍然为空

Array of pointers remaining null despite being directly set

我在长度为 [sizeX][sizeY] 的二维数组中有一个包含 'cell' 个对象的列表。这些 Cell 对象包含一个 *Cell 类型的数组,该数组应指向给定单元格的每个相邻单元格,格式为北、东、南、西(切勿吃湿华夫饼)。

这个数组叫做compass,定义长度为4。初始化单元格后(此时compass的所有值都设置为nullptr ),我有一个循环,它试图用指向附近适当单元格的指针填充 Cell.compass

然而,我发现尽管如此,在每个单元格中我发现 compass 仍然充满了空值。

在这个循环中,我还 运行 一个函数 Cell::computeTopology() 填充有效非空索引的向量(它是 Cell 的 属性) compass 个。这同样是空的。

我在调用此函数前后都设置了断点,效果完全相同。无论如何,我也会包括这个功能。我非常困惑,非常感谢这里的一些帮助。

问题区域:

  const int sizeX = SCREEN_WIDTH / SCALE;
    const int sizeY = SCREEN_HEIGHT / SCALE;
    Cell cells[sizeX][sizeY];
    for (int x = 0; x < sizeX; x++){
        for (int y = 0; y < sizeY; y++){
            cells[x][y].setPos(x, y);
            cells[x][y] = Cell();
            //cells[x][y].setColor(rand() % 255, rand() % 255, rand() % 255);
        }
    }
    for (int x = 0; x < sizeX; x++) {
        for (int y = 0; y < sizeY; y++) {
            Cell c = cells[x][y];
            if (x - 1 >= 0) {

                c.compass[3] = &cells[x - 1][y];
            }
            if (x + 1 < (SCREEN_WIDTH / SCALE)) {

                c.compass[1] = &cells[x + 1][y];

            }
            if (y - 1 >= 0) {

                c.compass[0] = &cells[x][y - 1];

            }
            if (y + 1 < (SCREEN_HEIGHT / SCALE)) {

                c.compass[2] = &cells[x][y + 1];
            }
            c.computeTopology();
        }
    }

computeTopology()函数

void Cell::computeTopology()
{
    int i = 0;
    for (Cell *c : compass) {
        if (c != nullptr) {
            notNull.push_back(i);
            i++;
        }
    }
}

改变

Cell c = cells[x][y]; // make a copy

Cell& c = cells[x][y];

您想修改数组的项目,而不是复制。

另一个问题

cells[x][y].setPos(x, y);
cells[x][y] = Cell(); // ?

您正在通过调用 setPos 来设置 cells[x][y] 的某些成员,然后在默认情况下覆盖 cells[x][y] 构造的 Cell 对象。我认为应该删除上面代码中的第二行。


你的话

which populates a vector (which is a property of Cell) of the valid non-null indexes of compass

所以 i 索引应该随着 for 循环的每次迭代而前进:

  int i = 0;
  for (Cell *c : compass) {
        if (c != nullptr) {
            notNull.push_back(i);
        }
        ++i; // moved
  }