C++读取.txt文件到二维Char*数组时出现EXC_BAD_ACCESS错误求助
解决POS程序读取文件时的内存访问错误
嘿,我懂你现在卡在哪了——这个EXC_BAD_ACCESS错误完全是因为你的二维char*数组没正确初始化内存导致的,我给你拆解清楚,再帮你把代码改对:
错误根源分析
你声明的char *array[4][3]是个4行3列的指针数组,但每个char*元素都只是个空指针(默认指向0x0地址)。当你执行inFile >> array[i][j]时,程序试图把文件里读来的字符串写入空指针指向的内存,这直接触发了内存访问违规,就出现了你看到的错误。
最省心的解决方案:用std::string代替char*
对于C++新手来说,std::string是处理字符串的最优选择,它会自动帮你管理内存,不用手动分配释放,彻底避开这类问题。下面是修改后的完整代码:
#include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; // 新手阶段用这个简化代码,后续再慢慢理解命名空间 string fileLoc(){ string file; cout << "Enter file name or location: "; cin >> file; return file; } // 将参数改为string二维数组 void getMenu(string fileName, string array[][3]){ ifstream inFile(fileName); if (!inFile){ cout << "File failed to open\n"; return; // 文件打开失败要提前返回,避免后续无效操作 } for (int i = 0; i < 4; ++i){ for (int j = 0; j < 3; ++j){ inFile >> array[i][j]; cout << array[i][j] << " "; } cout << endl; // 每行结束换行,输出更清晰 } inFile.close(); } int main (){ string array[4][3]; // 把char*数组替换成string数组 string fileName; vector<string>order; fileName = fileLoc(); getMenu(fileName, array); return 0; }
要是课堂要求必须用char*(不推荐新手这么做)
如果因为作业要求必须使用char*,那你得给每个指针分配足够的内存来存储读取的字符串,比如:
// 在getMenu的循环里先分配内存 for (int i = 0; i < 4; ++i){ for (int j = 0; j < 3; ++j){ array[i][j] = new char[50]; // 分配50字节内存,足够存菜单内容 inFile >> array[i][j]; cout << array[i][j] << endl; } } // 记得最后要释放内存,避免内存泄漏 for (int i = 0; i < 4; ++i){ for (int j = 0; j < 3; ++j){ delete[] array[i][j]; } }
但这种方式需要手动管理内存,很容易出错,所以还是优先推荐std::string的方案。
内容的提问来源于stack exchange,提问作者Dexter Silva
相关产品推荐
相关产品推荐

