0

I'm trying to make the move function from pset3 work but it keeps saying "segmentation fault" when I try to move the piece in the top-right corner. This always happens, even if the blank space is next to the top-right corner piece. I also get a "segmentation fault" when I try to move the piece in the top-left corner, but only if the blank space is not next to it. Can anyone explain to me why this happens and what I can do to prevent it from happening?

bool move(int i, int j[d][d])
{
    for (int y = 0; y<d; y++)
    {
        for (int x = 0; x<d; x++)
        {
            if (j[y][x] == i)
            {
                int swap;
                if (j[y-1][x] == 0)
                {
                    swap = j[y][x];
                    j[y][x] = j[y-1][x];
                    j[y-1][x] = swap;
                    return true;
                }
                else if (j[y+1][x] == 0)
                {
                    swap = j[y][x];
                j[y][x] = j[y+1][x];
                j[y+1][x] = swap;
                return true; 
                }
                else if (j[y][x-1] == 0)
                {
                    swap = j[y][x];
                    j[y][x] = j[y][x-1];
                    j[y][x-1] = swap;
                    return true;
                }
                else if (j[y][x+1] == 0)
                {
                    swap = j[y][x];
                    j[y][x] = j[y][x+1];
                    j[y][x+1] = swap;
                    return true;
                }
                else 
                {
                    return false;
                }
            }
        }    
    }
    printf("Tile is not on the board\n");
    return false;
1

Use like if (y > 0 && j[y-1][x] == 0) and if (y < d-1 && j[y+1][x] == 0) (equivalent checks for x on the other lines) to prevent this from being evaluated for invalid coordinates.

You must log in to answer this question.

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