0

I'm trying to set the size of an array to an input received by the program, currently the size of the array is defined as a const static int.

Board.h

#include <iostream>
using namespace std;

class Board {
private:
    const static int BOARDSIZE = 5;
    char board[BOARDSIZE][BOARDSIZE];

    const char p1Symbol = 'R';
    const char p2Symbol = 'B';
    const char trail = 'O';
    const char crash = '*';

    int p1Row;
    int p1Col;
    int p2Row;
    int p2Col;
public:
    void setBoardSize(int size);
    bool isValidMove(int row, int col);
    bool isValidInput(char input);
    bool getNextMove();
    void initializeArray();
    void drawHorizontalSeparator();

    void drawSeparatedValues(int row);
    void displayBoard();
};

Main

#include <iostream>
#include "Board.h"

using namespace std;

int main() {
    int size;
    cout << "Enter and integer between 4 and 20 for the BoardSize: " << endl;
    cin >> size;
    Board b;
    b.setBoardSize(size);
    b.initializeArray();
    b.displayBoard();

    bool done = false;

    while (!done) {
        done = b.getNextMove();
    }

    return 0;
}

I'm trying to use this function called setBoardSize to change the size of the board in the Board.H file. I've tried removing const static but then I get all sorts of errors. Apparently it isn't possible to define an array that doesn't have a predefined size?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Roland
  • 61
  • 7
  • If you are not allowed to use standard library containers for this task, I recommend making that fact clear in the question. If you do not, you will receive answers using nothing but library containers because that's the most-sane way to do it. – user4581301 Sep 07 '19 at 02:35
  • Use `std::vector` (if you're happy to have one dimensional indexing) or a `std::vector >` if you insist on two dimensions. Either works, since `std::vector` is a (templated) resizable container of specified types, and can contain other resizable containers. – Peter Sep 07 '19 at 02:36

1 Answers1

0

Instead of char board[BOARDSIZE][BOARDSIZE] go for std::vector<char>(BOARDSIZE * BOARDSIZE, 0) and access elements as vector[y * BOARDSIZE + x] where x and y run within <0, BOARDSIZE).

You would resize simply as vector.resize(size * size).

Tom Trebicky
  • 638
  • 1
  • 5
  • 11
  • 1
    Good suggestion. A slight improvement is to wrap the vector in a data structure that makes it look 2D so you can't accidentally mess up the indexing in one spot without messing it up everywhere. [Here's a good example example wrapper](https://stackoverflow.com/a/2076668/4581301). – user4581301 Sep 07 '19 at 02:34