【发布时间】:2014-03-14 00:17:05
【问题描述】:
我一直在搜索 Stack Overflow 和 cplusplus 论坛,但没有成功。我是 C++ 新手,目前正在为学校项目开发游戏。我在创建、填充、销毁 2d 指针数组时没有问题,并且在我的游戏中使用了一个,它工作得很好。
我为玩家创建了一个新类并将二维数组移动到该类中。现在,当我尝试运行我的程序时,我遇到了分段错误。任何人都可以让我了解为什么会这样吗? 粗体我不能简单地使用std::vector<>,因为指针的二维数组是必需的。
class Player
{
public:
Player();
...
short** allocate_2d_array();
....
protected:
short **board;
static const short BOARD_DIMENSIONS;
...
};
功能
short** Player::allocate_2d_array()
{
short **array2d;
// Insert columns
for(int i = 0; i < this->BOARD_DIMENSIONS; i++)
{
array2d[i] = new short[this->BOARD_DIMENSIONS];
// Fill in the numbers
for(int j = 0; j < this->BOARD_DIMENSIONS; j++)
{
array2d[i][j] = 0;
}
}
return array2d;
}
它的名字
Player::Player()
{
this->turns_taken = 0;
// Prepare the board
this->board = this->allocate_2d_array();
...
}
【问题讨论】:
-
也许你可以使用 :vector > board(BOARD_DIMENSIONS,vector
(BOARD_DIMENSIONS,0));替换 allocate_2d_array -
另外,我不知道您为什么希望
allocate_2d_array可以公开访问 -
不应该公开,复制粘贴出错。
标签: c++ class pointers dynamic-arrays