C++为含二维vector的结构体赋值出现Segmentation fault (core dumped)如何解决
C++拼图求解器段错误修复
核心错误原因
- 内层循环增量写错:原本遍历j的内层循环,错误写为
i++,导致i值会快速突破3的边界,触发非法内存访问。 - 二维vector未初始化空间:
Board结构体中的board成员默认是空vector,没有提前分配3行3列的存储空间,直接用[i][j]下标赋值属于访问未申请的内存,是段错误的直接诱因。 - 头文件缺失:使用
cout、cin没有引入<iostream>头文件,部分编译器会直接编译失败。 - 类型冗余:存储单个字符不需要用
vector<vector<string>>,改用vector<vector<char>>更合理。
修复后的完整代码
#include <iostream> #include <vector> #include <string> using namespace std; struct Board { // 改用char存储单个字符,减少冗余 vector<vector<char>> board; int blankx, blanky; }; Board getBoard(string state) { Board board; // 提前为二维vector分配3行3列的空间 board.board.resize(3); for (int i = 0; i < 3; i++) { board.board[i].resize(3); } int count = 0; for (size_t i = 0; i < 3; i++) { // 内层循环增量修正为j++ for (size_t j = 0; j < 3; j++) { board.board[i][j] = state[count]; if (state[count] == '#') { board.blankx = i; board.blanky = j; } count++; } } return board; } void findCost(string beginstate, string goalstate) { int cost = 0; Board initBoard = getBoard(beginstate); // 后续求解逻辑可在此补充 cout << "the optimal cost is : " << cost << "\n"; } int main() { string beginState, goalState; cout << "please enter the begin state:\n"; cin >> beginState; cout << "please enter the goal state:\n"; cin >> goalState; // 可选校验:避免输入长度错误导致越界 if (beginState.size() !=9 || goalState.size() !=9) { cout << "输入的状态长度错误,需要为9位字符" << endl; return 1; } findCost(beginState, goalState); return 0; }
内容的提问来源于stack exchange,提问作者Xin Nian
相关产品推荐
相关产品推荐

