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

如何在C++类中创建尺寸由txt文件决定的二维char数组并初始化

问题核心

C++标准不支持栈上可变长度数组(VLA),数组大小必须是编译期可确定的常量,你需要的运行时动态大小二维数组,推荐用std::vector实现,无需手动管理内存,兼容性最好。


修改后的完整代码

头文件 grid.h

#ifndef GRID_H
#define GRID_H
#include <vector>
#include <string>
#include <fstream>

class Grid
{
private:
    int height = 0;
    int width = 0;
    // 用vector嵌套实现动态二维数组
    std::vector<std::vector<char>> grid;

public:
    // 构造函数传入文件路径,直接完成文件读取和grid初始化
    Grid(const std::string& directory);
    // 对外暴露属性的getter
    int getHeight() const { return height; }
    int getWidth() const { return width; }
    const std::vector<std::vector<char>>& getGrid() const { return grid; }
};

#endif // GRID_H

源文件 grid.cpp

#include "grid.h"

Grid::Grid(const std::string& directory)
{
    std::fstream newfile;
    newfile.open(directory, std::ios::in);
    if (!newfile.is_open()) {
        // 可自定义文件打开失败的处理逻辑
        return;
    }
    std::string line;
    std::vector<std::string> allLines;
    // 先逐行读取所有文本内容
    while(std::getline(newfile, line)){
        // 过滤空行的逻辑,不需要可以直接删掉
        if (!line.empty()) {
            allLines.push_back(line);
        }
    }
    newfile.close();
    // 计算网格尺寸
    height = allLines.size();
    if (height == 0) {
        width = 0;
        return;
    }
    width = allLines[0].size();
    // 初始化网格并填充内容
    grid.resize(height, std::vector<char>(width));
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            grid[y][x] = allLines[y][x];
        }
    }
}

原有代码的核心错误说明

  • 类成员变量的初始化顺序早于构造函数执行逻辑,你在声明height/width时调用getSize(),此时文件还未读取,text为空,不可能拿到正确尺寸
  • C不支持运行时长度的栈上数组,char grid[height][width]语法本身不符合C标准,只能靠部分编译器扩展支持,稳定性极差
  • getSize()中return h, w;是逗号表达式,只会返回最后一个值w,无法同时返回两个参数
  • 所有循环条件写反,比如for (int ii = 1; ii > int(text.size()); ii++)初始值就不满足循环条件,循环根本不会执行
  • getGrid()中声明的static数组是全局生命周期,多次调用会覆盖内容,完全不适合作为类成员的存储载体

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:45:04