Two-dimensional char array trouble

Hi, I'm having some trouble making a two-dimensional array of char's, I'm going to use this array as a play board for a game.

This is my source:
Board.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef BOARD
#define BOARD 1
#include <iostream>
using namespace std;

class Board {
      public:
             Board();
             void draw();
             void init();
             char **field;
      private:
              int width;
              int height;
};
#endif 


Board.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include "Board.h"
#include <iostream>
#include <string>

using namespace std;

      Board::Board() {
                     cout << "Please enter the width of the playboard: " << endl;
                     cin >> width;
                     cout << "Please enter the height of the playboard: " << endl;
                     cin >> height;
                     **field = field[height][width];
                     }
                     
      void Board::draw()  { //test output
                         cout << field[0][0] << endl;
                     }
                     
      void Board::init() {
                         for (int b=0; b<width; b++) {
                             for (int a=0; a<height; a++) {
                                 field[a][b] = ' ';
                                 }
                             }
                         }


main.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
#include <cstdlib>
#include <iostream>
#include "Board.h"

int main()
{
    Board spel;
    spel.init();
    spel.draw();
    system("PAUSE");
    return 0;
};


I get no error's while compiling but the program crashes after input of height...
Can someone please tell me what I'm doing wrong?

Grtz
By the way, I'm a beginner C++ programmer so please explain in detail.

Thanks in advance
The problem is in the constructor:
1
2
3
4
5
6
7
Board::Board() {
     cout << "Please enter the width of the playboard: " << endl;
     cin >> width;
     cout << "Please enter the height of the playboard: " << endl;
     cin >> height;
     **field = field[height][width];//wrong
}


Read this article on multi dimensional arrays:
http://www.cplusplus.com/forum/articles/7459/
the problem is in Board.cpp line 12. First of all you are asking the user the size of the 2d array so the the size is not fixed when you are writing your program. Thus you have to allocate the memory dynamically that is at program run-time and not the compile time.

just replace that line 12 with

1
2
3
field= new int*[height];
    for (int i=0;i<height;i++)
    field[i] = new int [width];


mind you, you are only allocating memory for the array in the constructor and not assigning values to the elements of the array....
Thanks for the help, I guess I have to learn more about using pointers...
Topic archived. No new replies allowed.