如何解决C++编写井字棋时数组操作触发的Segmentation Fault问题
问题排查与修复
导致段错误的核心原因
- 数组越界访问:你定义的
board是string[3][3]类型,合法下标范围为0~2,但代码中多处访问board[3][3](turn函数返回值、main函数中赋值操作),属于访问数组外内存,直接触发段错误。 - 位置计算逻辑错误:当输入
position为3的倍数时,position % 3结果为0,(position %3) -1得到-1,出现负下标越界;同时position /3的计算逻辑会导致输入3/6/9时行号计算错误,比如输入3时,3/3=1,错误定位到第二行。
其他逻辑错误
- 变量作用域错误:
player_turn在if/else代码块内定义,出块后即销毁,后续无法使用,目前代码固定写入"X",不管O的回合都会填充X。 - 无输入校验:没有判断输入是否在1-9范围内、也没有判断所选位置是否已被占用,容易触发异常。
- 函数设计冗余:C++中数组传参默认是传址,
turn函数内对board的修改会直接作用到原数组,无需设置返回值再赋值。
修复后完整代码
#include <iostream> using namespace std; void print_board(string board[3][3]) { cout << " | | " << endl; cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << " " << endl; cout << "_____|_____|_____" << endl; cout << " | | " << endl; cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << " " << endl; cout << "_____|_____|_____" << endl; cout << " | | " << endl; cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << " " << endl; cout << " | | " << endl; } void turn(string board[3][3], bool xturn) { int position; cout << "请输入落子位置 (1 - 9): "; cin >> position; // 输入范围校验 if (position < 1 || position > 9) { cout << "输入非法,请输入1-9之间的数字" << endl; return; } int row = (position - 1) / 3; int col = (position - 1) % 3; // 落子位置占用校验 if (board[row][col] != " ") { cout << "该位置已被占用,请重新选择" << endl; return; } string player_turn = xturn ? "X" : "O"; board[row][col] = player_turn; } int main(void) { string board[3][3] = {{" ", " ", " "}, {" ", " ", " "}, {" ", " ", " "}}; bool xturn = true; while (true) { print_board(board); turn(board, xturn); xturn = !xturn; } return 0; }
内容的提问来源于stack exchange,提问作者FreddieLumsden
相关产品推荐
相关产品推荐

