简体   繁体   English

将二维指针数组初始化为 C++ 中的成员变量

[英]Initializing a 2D array of pointers as a member variable in C++

I've been searching around Stack Overflow and the cplusplus forums with no luck.我一直在寻找 Stack Overflow 和 cplusplus 论坛,但没有运气。 I am new to c++ and I'm currently working on a game for a school project.我是 C++ 新手,目前正在为学校项目开发游戏。 I have no problem creating, filling, destroying a 2d array of pointers and was using one in my game and it was working great.我在创建、填充、销毁二维指针数组时没有问题,并且在我的游戏中使用了一个,并且效果很好。

I created a new class for a player and moved the 2d array into that class.我为玩家创建了一个新类并将二维数组移动到该类中。 Now when I try to run my program I get a segmentation fault.现在,当我尝试运行我的程序时,出现分段错误。 Can anyone give me some insight into why this is happening?谁能让我深入了解为什么会发生这种情况? bold I can't simply use a std::vector<> because the 2d array of pointers is a requirement.粗体我不能简单地使用std::vector<>因为需要二维指针数组。

class Player
{
public:
  Player();
  ...
  short** allocate_2d_array();
  ....
protected:
  short **board;
  static const short BOARD_DIMENSIONS;
  ...
};

The function功能

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;
}

Where it's called哪里叫

Player::Player()
{
  this->turns_taken = 0;
  // Prepare the board
  this->board = this->allocate_2d_array();
  ...
}

The first line of the body of your for loop dereferences the pointer array2d (using the square bracket operator) before you've allocated any memory for it, or initialized it.在为它分配任何内存或初始化它之前,for 循环主体的第一行取消引用指针array2d (使用方括号运算符)。

To avoid this issue, you'll have to allocate the first dimension of your array before entering your for loop.为避免此问题,您必须在进入 for 循环之前分配数组的第一个维度。 Once you've allocated this array of pointers, you can then allocate BOARD_DIMENSIONS arrays of short s and store the pointers to them in the elements of the first array.一旦分配了这个指针数组,就可以分配BOARD_DIMENSIONSshort数组并将指向它们的指针存储在第一个数组的元素中。

Something like:就像是:

short** array2d = new short*[BOARD_DIMENSIONS];
for (size_t u = 0; u < BOARD_DIMENSIONS; ++u)
{
    array2d[u] = new short[BOARD_DIMENSIONS];
    // You could then use memset to initialize the array, or
    // use a for loop, like in your example:
    for (size_t v = 0; v < BOARD_DIMENSIONS; ++v)
    {
        array2d[u][v] = 0;
    }
 }

Make sure when you're done with the memory that you release it properly, using operator delete []使用operator delete []确保在完成内存后正确释放它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM