Home > Back-end >  Function output wrong when using printf
Function output wrong when using printf

Time:12-29

printf("\n%d",NN NE ND SD SE SS E D);

This is my functions when I call checkmoves in the main function they give me a value of 4 that it is correct but when I add the printf above to check some values to trying solve another problem the function checkmoves give me back 13 instead of 4.

Note that I call in main like printf("\n%d", checkmoves(board,'o'));

int count_flips_dir(char board[8][8],int line, char col,int delta_line,int delta_col,char color){
    int i;
    if(board[line delta_line][col delta_col]=='.'){
        return 0;
    }
    if (delta_line line<=7 && delta_line line>=0){
        if (delta_col col<=7 && delta_col col>=0){
            for(i=0;board[line delta_line][col delta_col]!=color;i  ){
                line=delta_line line;
                col=delta_col col;
                if(board[line delta_line][col delta_col]=='.'){
                return 0;
                }
            }
        }
    }
    return i;
        
}
int flanked(char board[8][8],int line,char col,char color ){
    int NN = count_flips_dir(board,line,col,-1,0,color);
    int ND = count_flips_dir(board,line,col,-1,1,color);
    int NE = count_flips_dir(board,line,col,-1,-1,color);
    int SS = count_flips_dir(board,line,col,1,0,color);
    int SD = count_flips_dir(board,line,col,1,1,color);
    int SE = count_flips_dir(board,line,col,1,-1,color);
    int D = count_flips_dir(board,line,col,0,1,color);
    int E = count_flips_dir(board,line,col,0,-1,color);
    
    return NN NE ND SD SE SS E D;
}
int checkmoves(char board[8][8],char color){
    int i;
    int count=0;
    char j;
    for(i=0;i<8;i  ){
        for(j=0;j<8;j  ){
            if (board[i][j]=='.'){
                if (flanked(board,i,j,color)>0){
                    count  ;                
                }
            }        
        }
    }
    return count;
}

CodePudding user response:

In count_flips_dir you test if(board[line delta_line][col delta_col]=='.') before checking that the initial move stays inside the board.

Then you test that the initial move stays inside the matrix to search for the color, but not the subsequent ones.

Furthermore, the function returns i uninitialized if the initial move goes outside of the board.

I am not sure what the function should return in this case, probably 0.

Here is a modified version:

int count_flips_dir(char board[8][8], int line, int col,
                    int delta_line, int delta_col, char color) {
    for (int i = 0;; i  ) {
        line  = delta_line;
        col  = delta_col;
        if (line < 0 || line >= 8 || col < 0 || col >= 8)
            return 0;
        if (board[line][col] == color)
            return i;
        if (board[line][col] == '.')
            return 0;
    }
    return i;
}
  • Related