Ошибка сегментации при попытке взаимодействия с 2D-массивом C ++ - PullRequest
0 голосов
/ 06 марта 2020

Я пытаюсь взаимодействовать с двумерным массивом через класс Board. Однако я получаю ошибку сегментации при запуске основного файла, содержащего этот код:

#include "Board.h"

int main(int argc, char** argv)
{
  int height = 0;
  int width = 0;
  int pop_density = 0.8;

  Board* c = new Board(height,width);
  c->print();
  c->populate(pop_density);
  c->print();

  //for (i )
  cout << c->read_char_at_index(1,2) << endl;

  delete c;

  return 0;
}

Это плата. cpp Код:

#include "Board.h"

//in board: make a fucntion that pulls from file

Board::Board(int h, int w)
{
  m_height = h;
  m_width = w;
  m_array = new char* [m_height];
  for (int i = 0; i < m_height; ++i)
  {
    m_array[i] = new char[m_width];
    for (int j = 0; j < m_width; ++j)
    {
      m_array[i][j] = '-';
    }
  }
  cout << "Made board" << endl;
}

Board::~Board()
{
  for (int i = 0; i < this->m_height; ++i)
  {
    delete[] this->m_array[i];
  }
  delete[] this->m_array;

  cout << "Destructed Board" << endl;
}

void Board::print()
{
  for (int i = 0; i < this->m_height; ++i)
  {
    for (int j = 0; j < this->m_width; ++j)
    {
      cout << this->m_array[i][j] << " ";
    }
    cout << endl;
  }
}

void Board:: populate(double density)
{
  //seeding rand with time
  srand(time(NULL));
  int totalCells = this->m_height * this->m_width;
  int cellsToFill = round(totalCells * density);
  int cellsFilled = 0;

  for (int i = 0; i < cellsToFill; ++i)
  {
    int randomRow = rand() % this->m_height;
    int randomColumn = rand() % this->m_width;

    this->m_array[randomRow][randomColumn] = 'X';
  }
}

void Board:: write_char_at_index(int height, int width, char z)
{
  cout << "pre" << endl;
  cout << height << " " << width << endl;
  m_array[height][width] = z;
  cout << "Wrote" << endl;
}

char Board:: read_char_at_index(int height, int width)
{
  return m_array[height][width];
  cout << "read" << endl;
}

и плата. h Код:

#ifndef BOARD_H
#define BOARD_H

#include <iostream>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;

//This class is used to make a Board object

class Board
{
  public:
    Board(int h, int w);
    ~Board();
    void print(); // Prints the board to cout
    void populate(double density); // Populates board based on density input
    void write_char_at_index(int height, int width, char z);
    char read_char_at_index(int height, int width);

  private:
    char** m_array; // 2D array dynamically allocated during runtime
    int m_height;
    int m_width;
};

#endif

Любая помощь или совет будут полезны, так как я уже спросил двух одноклассников, и они не уверены, в чем проблема. Я точно знаю, что индекс, которому я пытаюсь присвоить значение символа, не выходит за пределы.

1 Ответ

1 голос
/ 06 марта 2020

Входными параметрами read_char_at_index являются (1,2) в основной функции. Однако объект Board c имеет высоту = 0 и ширину = 0. Вы можете изменить значение высоты и ширины на достаточно большие значения, такие как 10, 10.

    int height = 10;
    int width = 10;
    int pop_density = 0.8;

    Board* c = new Board(height, width);
    c->print();
    c->populate(pop_density);
    c->print();

    cout << c->read_char_at_index(1, 2) << endl;

Программа может работать без ошибки сегментации.

Примечание. Функции «write_char_at_index» и «read_char_at_index» могут проверять входные значения (высоту и ширину), чтобы обеспечить безопасный доступ к члену m_array.

    if (height >= this->m_height || width >= this->m_width)
    {
        return;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...