简体   繁体   中英

New to c++ and getting a odd segmentation fault error

I'm continuing to get this odd error and it is printing my solution incorrectly. I believe it has to do with the printSolution() method because it is prints "QQ * QQQQQ" (although this is incorrect) and then I get a segmentation fault error.

Here is my .cpp :

#include "NQueens.h"
#include<iostream>

using namespace std;

NQueens::NQueens()
{

}

NQueens::~NQueens()
{
    cout <<"Destroying an object"<<endl;
}


void NQueens::printBoard(int board[], int N)
{
    std::cout<<endl;
    for(int i = 0; i<N; i++)
    {
        int chessBoard[N];
        chessBoard[board[i]] = 1;
        for(int j =0; j<N; j++)
        {
            if(chessBoard[j]==0)
            std::cout<<"* ";
            else
            std::cout<<"Q ";
        }
    std::cout<<endl;
    }
}

bool NQueens::safePlace(int row, int col, int board[])
{
    for(int i = 0; i<row; i++)
    {
        if((board[i] == col) || (i-row)==(board[i]-col) || (i-row) == (col-board[i]))
        return false;
    }
    return true;
}

void NQueens::solve(int N)
{
    int board[N];
    int row = 0;
    while(row<N && row>-1)
    {
// condition that the row is occupied and the queen is safe to place
        if(board[row]>-1 && board[row]<(N-1))
        {
            for(int i = board[row]+1; i<N; i++)
            {
                //checks for safety
                if(safePlace(row, i, board))
                {
                    board[row]=i;
                    ++row;
                    break;
                }
                else if(i==(N-1))
                {
                    board[row]=-1;
                    --row;
                }
            }
        }
        else if(board[row]==-1 && board[row]<(N-1))
        {
            for(int i = 0; i<N;i++)
            {
                if(safePlace(row, i, board))
                {
                    board[row]=i;
                    ++row;
                    break;
                }
                else if(i==(N-1))
                {
                    board[row]=-1;
                    --row;
                }
            }
        }
        else
        {
            board[row]=-1;
            --row;
        }
    }
    printBoard(board,N);
}

int main()
{
    NQueens driver;
    driver.solve(8);

    return 0;
}

Could this be because of loop statement reaching null?

I don't see where solve() initializes the contents of board before it gets used.

As such, the call to safePlace() passes the board array initialized to junk values, triggering the segfault.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM