首页 > 解决方案 > 在类中用 C++ 初始化一个 char**

问题描述

我正在尝试初始化一个 char**,它将充当大小为 (board_size * board_size) 的二维 char 数组。但是,我无法在网格中填充字符“-”,当我到达该行时,我得到了退出代码 11,这是一个段错误。如何将数据分配给动态二维数组。char ** 是使用错误的类型吗?我错过了什么?

代码:

class World
{
    public:

    World(int num_ants, int num_doodlebugs, int board_size)
    {
        this->board_size = board_size;
        this->num_ants = num_ants;
        this->num_doodlebugs = num_doodlebugs;
        this->board = new char*[board_size*board_size];

        for(int i = 0; i < board_size; i++)
        {

            for(int j = 0; j < board_size; j++)
            {
                this->board[i][j] = '-';
            }
        }

        cout << "Instantiated object" << endl;
    };

    void printWorld()
    {
        cout << "Printing World" << endl;

        for(int i = 0; i < this->board_size; i++)
        {
            for(int j = 0; j < this->board_size; j++)
            {
                cout << this->board[i][j] << " ";
            }

            cout << endl;
        }
    }

    private:
        int num_ants;
        int num_doodlebugs;
        int board_size;
        vector<Ant> ants;
        vector<Doodlebug> doodblebugs;
        char **board;
};

标签: c++pointers

解决方案


如果你想在 C++ 中做 C 风格的数组,你需要像在 C 中一样管理它们。所以如果你有一个T**,那需要指向一个 的数组T*,每个数组都指向一个 的数组T。在你的情况下:

    this->board = new char*[board_size];
    for(int i = 0; i < board_size; i++) {
        this->board[i] = new char[board_size];
        for(int j = 0; j < board_size; j++) {
            this->board[i][j] = '-';
        }
    }

这样做的缺点是它不是异常安全的,并且需要在析构函数中进行显式清理(如果需要,还需要在复制 ctor 和赋值运算符中进行更多工作)。最好使用std::vector<std::vector<char>>

    this->board.resize(board_size);
    for(int i = 0; i < board_size; i++) {
        this->board[i].resize(board_size);
        for(int j = 0; j < board_size; j++) {
            this->board[i][j] = '-';
        }
    }

推荐阅读