DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Dynamic arrays in a class (http://www.daniweb.com/forums/thread161527.html)

chasee Dec 9th, 2008 7:12 pm
Dynamic arrays in a class
 
I'm working on a program that has a class Board, and two inherited classes that will implement different games, but I'm having problems with setting up the initial Board class. The problem is that I don't know how to make it so the board array in the protected section of the Board.h file takes on the values input in a and b in the main.cpp file.

Here's my main.cpp
#include <iostream>
#include "Board.h"

using namespace std;

int main()
{
    Board Game;
    int a, b;
    cout << "enter a: ";
    cin >> a;
    cout << endl << "enter b: ";
    cin >> b;
    cout << endl;
    Game.set_board(a,b);
    Game.display();

    return 0;
}
my Board.cpp
#include "Board.h"
#include <iostream>

using namespace std;

Board::Board()
{

}

void Board::display()
{
    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < height; j++)
        {
            cout << board[i][j] << " ";
        }
        cout << endl;
    }
}

void Board::set_board(int a, int b)
{
    width = a;
    height = b;

    int num = 1;

    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < height; j++)
        {
            board[i][j] = num++;
        }
    }
}
and my Board.h file
#ifndef BOARD_H_INCLUDED
#define BOARD_H_INCLUDED

class Board
{
    public:
    Board();
    void display();
    void set_board(int, int);

    protected:
    int height, width;
    int board[4][4];
};

#endif // BOARD_H_INCLUDED

mahlerfive Dec 9th, 2008 7:57 pm
Re: Dynamic arrays in a class
 
Instead of: int board[4][4];
Replace with: int** board;
Now we can dynamically allocate space for the 2D board array.

In set_board(), we need to do the dynamic allocation like so:
// First allocate for the first dimension
board = new int*[height];

// Now allocate for the second dimension
for( int i = 0; i < height; i++ ) {
  board[i] = new int[width];
}


All times are GMT -4. The time now is 5:57 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC