不直接访问数组的指针数组交换

Pointer array swap without direct access to array

尝试使用命令让我的角色在矩阵中移动。但是我的动作不太对。

这是上传到 WandBox 以保存有问题的 space 的代码:WandBox

预计: 我希望当我按下 w 键时,地图上的点“*”会向上移动。通过交换两个指针。

结果: 交换没有任何作用,即使指针确实发生了变化。

void Player::update(Node * neighbors[8], const char c,Node * self)
{
    switch (c)
    {
    case 'w':
        move(neighbors[1],self);
        break;
    default:
        break;
    }
}

//This is right issent it?
void Player::move(Node * newspot, Node * oldspot)
{
    Node* temp = newspot;
    newspot = this;
    oldspot = this->standingTile;
    this->standingTile = temp;
}

我不明白。我确实尝试了一些不同的东西,比如指向数组指针的指针,所以希望我的例子看起来不疯狂。

试试这个:

void Player::update(Node * neighbors[8], const char c,Node * self)
{
    switch (c)
    {
    case 'w':
        move(&neighbors[1],&self);
        break;
    default:
        break;
    }
}

void Player::move(Node ** newspot, Node ** oldspot)
{
    Node* temp = *newspot;
    *newspot = this;
    *oldspot = this->standingTile;
    this->standingTile = temp;
}

我想我明白了,原来我想做的事情叫做 "multiple indirection"。

正如@Peter 所指出的那样,仅以这种方式交换指针并非易事。

virtual Node* update(Node** neighbors[8], char& c);

正是我所需要的,我将一个指针数组传递给存储数组中的指针,以便我可以在顶层交换它们。

int* myArrayOfInts[MAP_SIZE*MAP_SIZE];

我可以在哪里保留所有对象的准确列表。

然后当我需要将其作为二维数组进行操作时:

int*(*map)[MAP_SIZE] = (int*(*)[MAP_SIZE])myArrayOfInts; //Cast as 2d Array temporarily.

现在我可以将 map 视为普通的二维指针数组。

现在通过将指针传递给指针数组来调整父数组变得微不足道:

&map[x][y]

或者在我的例子中将它们存储在数组指针数组中....

Node** neighbors[8];
neighbors[0] = &map[x][y];

然后我可以将其传递给一个函数,允许我交换值而无需复制和移动整个对象。

哟狗,我给你放了leik指针,所以我们把指向你指针的指针放在指针数组中......