0

I have been getting segmentation fault for a couple of hours now, i tried alot of different things, anyone have any advice? thank you

bool move(int tile)
{

    int zerotile=board[d-1][d-1];
            if(tile==0){

            return false;
        }
for(int i=0;i<d;i++){

    for(int j=0;i<d;j++){

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

           }
           if(i<d-1){
                       if(board[i+1][j]==zerotile){
             board[i+1][j]=tile;
               board[i][j]=0;
               return true;
           }
           }
           if(j>0){
                      if(board[i][j-1]==zerotile){
              board[i][j-1]=tile;
               board[i][j]=0;

               return true;
           }
           }
          if(j<d-1){
                       if(board[i][j+1]==zerotile){
              board[i][j+1]=tile;
               board[i][j]=0;
               return true;
           }
          }

       }
    }
}
return false;}
3
  • you might want to edit your post for readability, the first couple of lines are missing
    – ronga
    Mar 1, 2016 at 3:03
  • Edited, thank you!
    – Omar Wagih
    Mar 1, 2016 at 14:45
  • @OmarWagih what is the size of the board array?
    – myckhel
    Nov 18, 2018 at 20:54

1 Answer 1

0

I see two problems with your move() function. First, look at the setup of the inner loop:

for(int j=0;i<d;j++)

This is an infinite loop because the test is checking i, not j. This is almost certainly causing the seg fault. Let's assume that was a cut and paste typo, but it needs to be fixed.

Second, there's this line at the beginning of the function:

    int zerotile=board[d-1][d-1];

Because of this, the code will always treat the zero tile as being in the lower right corner. That condition is only known to be true when the board is initialized. After the first move, the zero tile could be anywhere.

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 .