-2

When I try to move a legal tile (i.e one adjacent to the 'blank' tile 0), nothing happens. If the tile is illegal the program functions as it should. Here is the move function:

bool move(int tile)
{
    for (int i = 0; i < d; i++)
    {
        for (int j = 0; j < d; j++)
        {
            if (board[i][j] == tile)
            {
                // stops program from going out of bounds
                if (j < d)
                {
                    if (board[i][j + 1] == 0)
                        {
                            swap(board[i][j], board[i][j + 1]);
                            return true;
                        }
                }

                if (j > 0)
                {
                    if (board[i][j - 1] == 0)
                        {
                            swap(board[i][j], board[i][j - 1]);
                            return true;
                        }
                }

                if (i > 0)
                {
                    if (board[i - 1][j] == 0)
                        {
                            swap(board[i][j], board[i - 1][j]);
                            return true;
                        }
                }

                if (i < d)
                {
                    if (board[i + 1][j] == 0)
                        {
                            swap(board[i][j], board[i + 1][j]);
                            return true;
                        }
                }
            }
        }
    }

    return false;
}

and the swap function:

void swap(int i, int j)
{
    int temp = i;
    i = j;
    j = temp;
}

What happens is the board remains looking the same with no changes made.

roncook
  • 287
  • 3
  • 13
  • 1
    You're passing `i` and `j` by value to the `swap` function. If you want to actually swap the variables in the caller's context, pass them via pointer. – Daniel Kamil Kozar Sep 08 '16 at 18:08
  • 1
    See: http://stackoverflow.com/questions/1501217/c-function-to-swap-values-in-2d-array – Jay Elston Sep 08 '16 at 18:11
  • 1
    Remember when you pass a *value* to a function, the function receives a *copy of the original* with its very own, and *very different* address. – David C. Rankin Sep 08 '16 at 18:48

1 Answers1

5

You need to use pointers to change the memory at board[i][j].
Try something like this

void swap(int *i, int *j)
{
    int temp = *i;
    *i = *j;
    *j = temp;
}

and then in your calling code

swap(&board[i][j], &board[i][j - 1]);
cleblanc
  • 3,678
  • 1
  • 13
  • 16
  • You should write `int *i, int *j` for readability, otherwise when you declare (e.g. `int* i, j, k;`) some may presume that `j & k` are `int *` -- which they are not. `int *i, j, k;` is less prone to misinterpretation. – David C. Rankin Sep 08 '16 at 18:51
  • Good point, I typically would write int *i. I'll correct the answer. – cleblanc Sep 08 '16 at 19:33