簡體   English   中英

代碼在OSX上運行,代碼塊VMbox中的分段錯誤

[英]Code runs on OSX, Segmentation fault in Codeblocks VMbox

因此,當我在OSX中運行它時,它可以正常運行,但是我的課程要求它在使用Codeblocks的Xubuntu VMbox中運行。 當我嘗試在Codeblocks或VMbox終端中運行它時,出現錯誤“分段錯誤(核心已轉儲)”。 這可能與需要導入不同的庫有關嗎? 我想我以前有這個問題。

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

int main(int argc, char const *argv[])
{
string filetoopen;
ifstream sudokutxtfile;
string txtline;
string sudokubox[9];
bool goodsudoku = true;
int i, j, row, column;

// Terminal input or default
if (argc == 2)
    filetoopen = argv[1];
else
    filetoopen = "sudokuboard.txt";
// Read in file, save to array, close file
sudokutxtfile.open(filetoopen);
while (getline(sudokutxtfile,txtline))
{
    sudokubox[row] = txtline;
    row++;
}
sudokutxtfile.close();
// Valid solution check
for (i = 0; i < 9; i++)
{
    for (j = 0; j < 9; j++)
    {
        // check whether sudokubox[i][j] is valid at the i's row
        for (column = 0; column < 9; column++)
            if (column != j && sudokubox[i][column] == sudokubox[i][j])
                goodsudoku = false;

        // check whether sudokubox[i][j] is valid at the j's column
        for (row = 0; row < 9; row++)
            if (row != i && sudokubox[row][j] == sudokubox[i][j])
                goodsudoku = false;

        // check whether sudokubox[i][j] is valid in the 3-by-3 box
        for (row = (i / 3) * 3; row < (i / 3) * 3 + 3; row++)
            for (column = (j / 3) * 3; column < (j / 3) * 3 + 3; column++)
                if (row != i && column != j && sudokubox[row][column] == sudokubox[i][j])
                    goodsudoku = false;
    }
}
// Output 
if (goodsudoku == true)
    cout << "valid" << endl;
else
    cout << "invalid" << endl;
return 0;
}

您聲明這些變量

int i, j, row, column

那你在這里做個作業

while (getline(sudokutxtfile,txtline))
{
    sudokubox[row] = txtline;
    row++;
}

row從未被初始化,因此無論您要寫入sudokubox[row]索引sudokubox[row]都可能超出范圍(或為負,或為綠色,或誰知道)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM