# pset3 move uses the wrong Blankspace value

Hello in my move function for fifteen, when it searches for an adjacent blank space, if the tile is on the edge and the "missing" adjacent spot happens to be before my correct spot in the code, it use the value of the missing spot. and i print this: Tile to move: 1 8 7 6 _ 4 3 _ 2 1 if my blank space is in board[i][j+1], it will also read the zero in board[i+1][j], and if the wrong spot is first in the program, it will use that value and use the wrong value. here is my code. I'm having trouble figuring out what is making the program grab the wrong value first.

``````bool move(int tile)
{
int temp;
int blankspace = 0;
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (board[i][j] == tile)
{
if (board[i][j+1] == blankspace)
{
temp = tile;
board[i][j] = blankspace;
board[i][j+1] = temp;
return true;
}
if(board[i+1][j] == blankspace)
{
temp = tile;
board[i][j] = blankspace;
board[i+1][j] = temp;
return true;
}
if (board[i-1][j] == blankspace)
{
temp = tile;
board[i][j] = blankspace;
board[i-1][j] = temp;
return true;
}
if (board[i][j-1] == blankspace)
{
temp = tile;
board[i][j] = blankspace;
board[i][j-1] = temp;
return true;
}

}
}
}
return false;
}
``````

It's a common error. Consider the case where d=3. Now, say that i=2 (or j=2, same logic). When i =2, what is i+1? Is it a valid index? No, but it also (almost always) won't generate an error. Instead, it will look at what might be at that position, as if it were valid. In reality, it's accessing whatever memory would represent that array element. Often, it will be 0, so it gets treated as a successful discovery of the blank.

You need to validate that the array elements you are accessing are within the valid range of array indexes. This applies to all 4 cases - I+1, j+1 must be < d and i-1 and j-1 must be >=0.

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