通过bool flag c ++显示多个错误

时间:2010-04-01 06:51:12

标签: c++ boolean

漫长的一夜,但坚持这一点,现在我的编译器出现“分段错误”..

基本上我正在尝试显示所需的所有错误(cout)。如果有多个错误,我将显示所有错误。

bool validMove(const Square board[BOARD_SIZE][BOARD_SIZE], 
               int x, int y, int value)
{
    int index;
    bool moveError = true;
    const int row_conflict(0), column_conflict(1), grid_conflict(2);    
    int v_subgrid=x/3;
    int h_subgrid=y/3;

    getCoords(x,y);

    for(index=0;index<9;index++)
        if(board[x][index].number==value){
            cout<<"That value is in conflict in this row\n";
            moveError=false;
            }

    for(index=0;index<9;index++)
        if(board[index][y].number==value){
            cout<<"That value is in conflict in this column\n";
            moveError=false;    
            }



    for(int i=v_subgrid*3;i<(v_subgrid*3 +3);i++){
        for(int j=h_subgrid*3;j<(h_subgrid*3+3);j++){
            if(board[i][j].number==value){
                cout<<"That value is in conflict in this subgrid\n";            
                moveError=false;
            }           
        }
    }
return true;
}

5 个答案:

答案 0 :(得分:1)

如果这是国际象棋棋盘,那么:

for(index=0;index<9;index++)

应该是:

for(index=0;index<8;index++)

甚至更好:

for(index=0;index<BOARD_SIZE;index++)

如果您有命名常量,请始终使用它们代替幻数。

答案 1 :(得分:0)

要找出触发SEGFAULT的确切行,请使用标记-ggdb进行编译(我假设您使用的是GCC),然后使用gdb运行程序(使用{{ 1}})。当GDB启动时,使用gdb ./name_of_the_program启动程序。它将在“main”处中断,然后执行run。让它一直运行到SEGFAULTs。一旦它被segfaulted,执行continue(或简称backtrace)以获得程序执行的回溯。回溯应包括导致SEGFAULT的确切行。

使用您从GDB获得的信息,您应该能够调试您的程序。但是,如果您需要更多帮助,请向我们提供bt的输出,以便我们提供更多帮助。

答案 2 :(得分:0)

检查你的指数。当您使用固定大小的数组时,它可能是一个错误的错误

答案 3 :(得分:0)

1)使用此功能而不是直接登上[x] [index]等:

    const Square& GetSquare(
      const Square board[BOARD_SIZE][BOARD_SIZE]&,
      int x,
      int y)
    {
      assert(x >= 0);
      assert(x < BOARD_SIZE);
      assert(y >= 0);
      assert(y < BOARD_SIZE);
      return board[x][y];
    }

测试您是否正在进行调试,以便assert(false)给出错误消息。写assert(false),查看消息,然后删除此行。没有这些断言,我根本无法信任你的代码。

2)不要使用幻数9和3。

3)考虑到int v_subgrid = x / 3;可以具有非零余数,例如,7/3 = 2,余数为1.并且2/3 = 0。如果这是你想要的,好的。请考虑一下。

答案 4 :(得分:0)

我希望您的seg值可能在以下部分中...(以及上面提到的(使用9而不是BOARD_SIZE)for proir two for-loops)...

for(int i=v_subgrid*3;i<(v_subgrid*3 +3);i++){ 
    for(int j=h_subgrid*3;j<(h_subgrid*3+3);j++){ 
        if(board[i][j].number==value){ 
            cout<<"That value is in conflict in this subgrid\n";             
            moveError=false; 
        }            
    } 

我建议你为你的功能(单元测试)编写一些强大的测试。传入设置为BOARD_SIZE - 2或更高的X或Y值意味着索引超出电路板的数组大小。

我想要了解的是,代码确实需要到位才能停止索引越界, 希望这也有帮助, 尼尔