这个简单的木炭填充器有什么问题

What is wrong with this simple char filler?

本文关键字:什么 问题 填充 简单      更新时间:2023-10-16

它看起来非常简单,但char数组的一个看似随机的点没有正确填充8。也没有编译器错误。很抱歉,这是一个很难回答的问题,但当我一个月前设计一个数独求解器时,我在运行几乎与此相同的代码时没有遇到任何问题。

#include <iostream>
using namespace std;
int main () {
//Initiates initial board.
char board[30][27];
//Fills entire board with b's to represent the edges of the board where the pac-man cannot go.
for (int control=0; control<31; control++) {
    for (int control2=0; control2<28; control2++) {
        board[control][control2]='8';
    }
}
//Code here filling the board with spaces representing where the pac-man can go.
//Temporary render of board.
for (int control=0; control<31; control++) {
    for (int control2=0; control2<28; control2++) {
        cout << board[control][control2];
    }
    cout << endl;
}
return 0;
}

它显然存在随机分割错误。

分割错误几乎不是随机的。你超出了数组的界限。CCD_ 1和板[][28]中的每一个都经过它们各自尺寸的末端。在这种情况下,您可能会覆盖main()的返回地址,因此您的程序会陷入杂草中,然后死亡,就像您在分段故障中看到的那样。将循环条件更改为:

control < 30

control2 < 27

你应该没事的。您也可以将数组的大小更改为board[31][28]

最重要的,您还应该学会使用调试器,您可以使用它来查找失败时controlcontrol2变量的值,这将为您解决此问题,而无需在此处询问。

您正在索引超过数组的最大值。

您可以对board进行的最大索引是board[29][26],因为您放置的30和27是元素的数量,数组的索引为零。

您超出了矩阵的大小。您有:

char board[30][27];

但你的循环是:

for (int control=0; control<31; control++) {
    for (int control2=0; control2<28; control2++) {

它们将使每个维度超出1。

因此,要么将矩阵更改为:char board[31][28];,要么减少循环的迭代。