【发布时间】:2021-12-09 11:07:50
【问题描述】:
我需要从我的 .txt 文件中逐行提取文本并将其存储到一个动态数组中,每次我从 .txt 文件中提取新行时都会分配新空间。我的代码似乎可以很好地拉出第一行并将其存储到第一个指针数组中,但是在第二个循环中,它似乎重置了所有指针数组,当我稍后尝试访问它时,这给了我内存分配错误。为什么会发生这种情况,尤其是当我在将内容存储到指针及其数组后不触摸它们时?
char** temp = nullptr;
char buffer[256];
int index = 0;
// Open File
fstream myFile;
myFile.open("pantry.txt", ios::in);
if (myFile.is_open())
{
while (!myFile.eof())
{
myFile >> buffer; // Pull line out of txt.file
temp = new char* [index + 1]; // Create new pointer
temp[index] = new char[strlen(buffer)+1]; // Create char array pointed at by new pointer
#pragma warning(suppress : 4996) // Turns off complier warning
strcpy(temp[index], buffer); //Copy buffer into new char array
index++; // Increment our index counter int
}
for (int i = 0; i < index; i++)
{
cout << temp[i] << endl;
}
如果分配和存储正确,我希望它能够准确地打印出 txt 文件。 相反,我得到了
Exception thrown at 0x7B9A08CC (ucrtbased.dll) in PE 12.4.exe: 0xC0000005: Access violation reading location 0xCDCDCDCD.
餐具室.txt
Basil
Flat Leaf Parsely
Thyme
Sage
Cumin
Steak Seasoning
Mace
Garlic Powder
【问题讨论】:
-
除非您有特定的理由不这样做(例如做不允许这样做的家庭作业),否则我强烈建议您创建`std::vector<:string>@987654325 @std::getline` 读取每一行,
std::push_back将每一行放入vector。有了这个,工作变得相当容易。 -
temp应该代表什么?使用模糊的变量名称,您甚至可能不会注意到您一遍又一遍地为该变量分配新的东西,总是泄漏(并丢失)它曾经指向的东西。 -
您的问题的根本原因(除了没有像@JerryCoffin 说的那样使用现代c++)是您重新分配
temp每个循环,因此第二个循环您丢失了第一个循环中存储的所有内容,等等。 -
哦,我也刚刚注意到您使用的是
while (!myFile.eof())。这通常也会导致问题。您通常需要while (read_from_file_succeeded())形式的东西。
标签: c++ arrays visual-c++ dynamic dynamic-arrays