0

我正在学习 C++,虽然我对 C# 有合理的理解,但我以前从未遇到过这个问题。使用一个简单的程序,将棋子放在一个虚构的棋盘(一个枚举数组)上,然后分配在开始时有棋子的方格,然后要求您提供坐标,程序会返回该方格上的内容。它显示正确的部分,但在非调试模式下总是会崩溃,并在 Visual Studio 调试中显示缓冲区溢出。它很短,所以我将显示所有代码。

#include <iostream>
#include <string>
using namespace std;
int main() {
enum Chessboard {
    Blank,
    Pawn,
    Rook,
    Knight,
    Bishop,
    King,
    Queen
};
Chessboard board[8][8] = { Blank };
for (int x = 1; x < 8; x++)
{
    board[1][x] = Pawn;
    board[8][x] = Pawn;
}
board[7][0] = Rook;
board[7][1] = Knight;
board[7][2] = Bishop;
board[7][3] = King;
board[7][4] = Queen;
board[7][5] = Bishop;
board[7][6] = Knight;
board[7][7] = Rook;
board[0][0] = Rook;
board[0][1] = Knight;
board[0][2] = Bishop;
board[0][4] = King;
board[0][3] = Queen;
board[0][5] = Bishop;
board[0][6] = Knight;
board[0][7] = Rook;

int X = 0;
int Y = 0;
bool Error = false;
cout << "Enter the coordinates of a square on a chessboard to see what is on there at    the start of the game (1 number at a time)" << endl;
do {
    cin >> X;
    X--;
    Error = false;
    if (X < 0 || X > 7)
    {
        cout << "That's not on the board" << endl;
        Error = true;
    }
} while (Error = false);
do {
    cin >> Y;
    Y--;
    Error = false;
    if (Y < 0 || Y > 7)
    {
        cout << "That's not on the board" << endl;
        Error = true;
    }
} while (Error = false);

string Name = "";
Chessboard Piece = board[X][Y];
switch (Piece)
{
case Blank: Name = "nothing";
    break;
case Pawn: Name = "a Pawn";
    break;
case Rook: Name = "a Rook";
    break;
case Knight: Name = "a Knight";
    break;
case Bishop: Name = "a Bishop";
    break;
case King: Name = "a King";
    break;
case Queen: Name = "a Queen";
    break;
default: Name = "Somehow you missed the board";
    break;
} 

cout << "On " << ++X << "," << ++Y << " there is " << Name << endl;

return 0;
}
4

5 回答 5

2

您正在超出矩阵的边界

   board[1][x] = Pawn;
   board[8][x] = Pawn;

您将其声明为 8x8,因此将使用索引 0..7。

于 2014-08-20T12:37:52.727 回答
2

你肯定会在这里超支:

Chessboard board[8][8] = { Blank };
for (int x = 1; x < 8; x++)
{
  board[1][x] = Pawn;
  board[8][x] = Pawn; 
}

没有board[8][]。你有board[0][]通过board[7][]可用的。

于 2014-08-20T12:38:07.457 回答
1

在 C、C++ 和 C# 中,数组的索引从 0 开始到数组的大小 - 1。例如这个循环

for (int x = 1; x < 8; x++)
{
    board[1][x] = Pawn;
    board[8][x] = Pawn;
}

必须重写为

for ( int x = 0; x < 8; x++)
{
    board[1][x] = Pawn;
    board[6][x] = Pawn;
}

假设数组定义为

Chessboard board[8][8] = { Blank };

此外,最好为幻数 8 引入一个助记名称,并在任何地方使用这个名称而不是数字。

于 2014-08-20T12:43:13.043 回答
0
for (int x = 0; x < 8; x++)
{
    board[0][x] = Pawn;
    board[7][x] = Pawn;
}

I think 7 is the maximum for this array.

于 2014-08-20T12:40:32.173 回答
0

正如其他人所说,它board[8][x] = Pawn是导致错误的原因。

尽管这似乎是一个测试程序,而不是将要投入生产的东西,但我还是要提醒一句警告,始终尽量避免在代码中使用数字/硬编码字符串/整数或其他任何东西,原因是你通常最终会做这样的事情。有一天,当项目投入生产时,您的老板可能会决定将值更改为 100 x 100,您将很难做事。

这样做的好方法:

static const int BoardSize = 10;

或者

#define BoardSize 10;
于 2014-08-20T13:30:56.033 回答