Dynamic arrays in a class

Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved

Join Date: Sep 2008
Posts: 4
Reputation: chasee is an unknown quantity at this point 
Solved Threads: 0
chasee chasee is offline Offline
Newbie Poster

Dynamic arrays in a class

 
0
  #1
Dec 9th, 2008
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
  1. #include "Board.h"
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. Board::Board()
  7. {
  8.  
  9. }
  10.  
  11. void Board::display()
  12. {
  13. for (int i = 0; i < width; i++)
  14. {
  15. for (int j = 0; j < height; j++)
  16. {
  17. cout << board[i][j] << " ";
  18. }
  19. cout << endl;
  20. }
  21. }
  22.  
  23. void Board::set_board(int a, int b)
  24. {
  25. width = a;
  26. height = b;
  27.  
  28. int num = 1;
  29.  
  30. for (int i = 0; i < width; i++)
  31. {
  32. for (int j = 0; j < height; j++)
  33. {
  34. board[i][j] = num++;
  35. }
  36. }
  37. }
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
Reply With Quote Quick reply to this message  
Join Date: Aug 2008
Posts: 77
Reputation: mahlerfive is an unknown quantity at this point 
Solved Threads: 16
mahlerfive mahlerfive is offline Offline
Junior Poster in Training

Re: Dynamic arrays in a class

 
0
  #2
Dec 9th, 2008
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:
  1. // First allocate for the first dimension
  2. board = new int*[height];
  3.  
  4. // Now allocate for the second dimension
  5. for( int i = 0; i < height; i++ ) {
  6. board[i] = new int[width];
  7. }
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC