You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从.txt文件提取文本存入动态二维数组?运行报错该如何解决?

问题根因

  1. 动态数组扩容逻辑完全错误
    你每次进入循环都会重新给temp分配一块长度为index+1的新堆内存,但完全没有把旧temp数组中已经存储的前index个字符串指针拷贝到新数组里,直接覆盖了temp的原有指向。新申请的数组里只有下标为index的位置被你赋值存储了当前读取的内容,其余位置都是未初始化的野指针。Windows调试模式下未初始化的堆内存会被填充为0xCD,所以你最后打印temp[0]等前面的元素时,访问0xCDCDCDCD地址直接触发了访问越界异常。同时你直接丢弃旧temp数组的指向,还造成了内存泄漏。
  2. 读取逻辑不符合需求
    你用myFile >> buffer是按空白符分割读取单个单词,而非读取整行,比如文件里的Flat Leaf Parsely会被拆成3次读取,和你逐行读取的需求不符。另外while (!myFile.eof())的写法是错误的,eof()是在读取失败后才会返回真,会导致最后一行内容重复读取。

修正后代码

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

int main()
{
    char** temp = nullptr;
    char buffer[256];
    int index = 0;

    fstream myFile;
    myFile.open("pantry.txt", ios::in);
    if (myFile.is_open())
    {
        // 改用getline读整行,直接判断读取结果避免eof误用
        while (myFile.getline(buffer, 256))
        {
            // 先申请扩容后的新数组
            char** new_temp = new char* [index + 1];
            // 把旧数组的内容全部拷贝到新数组
            for (int i = 0; i < index; i++)
            {
                new_temp[i] = temp[i];
            }
            // 释放旧数组的内存,避免泄漏
            delete[] temp;
            // temp指向扩容后的新数组
            temp = new_temp;
            // 存储当前读取的行内容
            temp[index] = new char[strlen(buffer) + 1];
#pragma warning(suppress : 4996)
            strcpy(temp[index], buffer);
            index++;
        }
        myFile.close();

        // 打印所有行
        for (int i = 0; i < index; i++)
        {
            cout << temp[i] << endl;
        }

        // 释放所有申请的堆内存,避免泄漏
        for (int i = 0; i < index; i++)
        {
            delete[] temp[i];
        }
        delete[] temp;
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者Dragoncupcake15

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:36:06