在类中C++启动字符**



我正在尝试初始化一个字符**,它将充当大小(board_size * board_size)的二维字符数组。但是,我在填充网格字符"-"时遇到问题,当我到达该行时,我得到退出代码 11,这是一个 seg 错误。如何将数据分配给动态 2D 数组。字符**使用的类型是否错误?我错过了什么?

法典:

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++中做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] = '-';
}
}

相关内容

最新更新