Question

I've been searching around Stack Overflow and the cplusplus forums with no luck. I am new to c++ and I'm currently working on a game for a school project. 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.

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();
  ...
}
Was it helpful?

Solution

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.

To avoid this issue, you'll have to allocate the first dimension of your array before entering your for loop. Once you've allocated this array of pointers, you can then allocate BOARD_DIMENSIONS arrays of shorts and store the pointers to them in the elements of the first array.

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 []

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top