为什么我的程序崩溃了

Why is my programming crashing

本文关键字:崩溃 程序 我的 为什么      更新时间:2023-10-16

由于某种原因,我的程序在循环中崩溃,我不确定问题的原因

这是我的密码。

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

int main()
{
    ifstream fin;
    ofstream fout;
    fin.open("dice.in");
    fout.open("dice.out");
    string line;
    int boardsize;
    int top;
    int side;
    fin >> boardsize >> top >> side;
    while(boardsize != 0)
    {
        int ** board;
        board = new int*[boardsize];
        //creates  a multi dimensional dynamic array
        for(int i = 0; i < boardsize; i++)
        {
            board[i] = new int[boardsize];
        }
        //loop through the 2d array
        for(int i = 0; i <= boardsize; i++)
        {
            getline(fin, line);
            for(int j = 0; j < boardsize; j++)
            {
                if(i != 0)
                board[i][j] = (int)line[j];
            }
            line.clear();
        }

        fin >> boardsize >> top >> side;
    }
    fin.close();
    fout.close();
}

这是我使用的输入文件

3 6 4
632
562
463
3 6 4
632
556
423
7 6 4
4156*64
624*112
23632**
4555621
6*42313
4231*4*
6154562
0 0 0
    //loop through the 2d array
    for(int i = 0; i <= boardsize; i++)
    {
        getline(fin, line);
        for(int j = 0; j < boardsize; j++)
        {
            if(i != 0)
            board[i][j] = (int)line[j];
        }
        line.clear();
    }

需要

    //loop through the 2d array
    for(int i = 0; i < boardsize; i++)         // note < instead of <=
    {
        getline(fin, line);
        for(int j = 0; j < boardsize; j++)
        {                                      // not I deleted if statement
            board[i][j] = (int)line[j];
        }
        line.clear();
    }

这是因为C++中的数组从索引0开始,所以当你分配一个大小为3的数组时,就像上面对board = new int*[boardsize];所做的那样,这个数组的索引将是0, 1, 2, ... boardsize-1,而你的算法使用的是1, 2, 3, ... boardsize,这将是一种越界访问,因为你只分配了n个块,而你正试图访问(实际上是修改)块n+1,这将导致分段错误。