0

My move function is not properly working. It will sometimes move numbers far away from where the blank space is, and also sometimes causes other numbers that should have been switched with the blank space to become blank spaces themselves. Here is my code:

bool move(int tile)
{
for (int i = d; i >= 1; i--)
{
    for (int j = d; j >= 1; j--)
    {
       if(board[i][j] == tile)
       {
           if(board[i-1][j] == 0 && i-1 >= 0)
           {
                int tmp = board[i][j];
                board[i][j] = board[i - 1][j];
                board[i - 1][j] = tmp;
               return true;
           }
           else if(board[i+1][j] == 0 && i+1 < d)
           {
               int tmp = board[i][j];
                board[i][j] = board[i + 1][j];
                board[i + 1][j] = tmp;
               return true;
           }
           else if(board[i][j-1] == 0 && j-1 >= 0)
           {
               int tmp = board[i][j];
                board[i][j] = board[i][j-1];
                board[i][j-1] = tmp;
               return true;
           }
           else if(board[i][j+1] == 0 && j+1 < d)
           {
               int tmp = board[i][j];
                board[i][j] = board[i][j+1];
                board[i][j+1] = tmp;
               return true;
           }
       }
    }
}
return false;
}

Thanks in advance.

1

The code is accessing memory outside of the board array. Note that the array board[x][y] is based on d. Both indexes x and y run from 0 to d-1. In the code, i and j are initialized as equal to d, so both indexes controlled by i and j are starting outside of the index limits. Unfortunately, this doesn't always result in an error, but the computer will access the memory that it thinks is referenced by these indexes. If the memory is allocated to the program, even if it is outside the array limits, it will use the data.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .