initializing 2d array in classes

Hello .
This is the code. and I'm getting the following errors, Any tips please ?

./file.h:15:42: error: a brace-enclosed initializer is not allowed here before ‘{’ token
../file.h:24:53: error: invalid in-class initialization of static data member of non-integral type ‘const int [10][12]’


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Maze{
public:
	static const int rows = 10;
	static const int columns = 12;
	  int Maze[rows][columns] =  { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
										{ 1, 0,0, 0, 1, 1, 0, 1, 0, 1, 0, 1 },
										{ 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0,1 },
										{ 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1 },
										{ 1, 1, 0, 1, 1, 1, 1,1, 1, 1, 0, 0 },
										{ 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1},
										{ 1, 1, 0,0, 0, 0, 1, 1, 1, 1, 1, 1},
										{ 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0,1},
										{ 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1},
										{ 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1} };
};
Hi mgehad,

The problem with your code is that you're doing something forbidden with your 2D array. You CANNOT initialize a non-static member in a class declaration.

This explains why you can initialize the rows, and columns static variables, because they are static. And it explains why you have an error with your array, because it is non-static.

Another thing, you cannot have a member with the same name. (I'm not sure this is true, but it's anyway a bad idea.) So let's call your Maze array, MazeArray.
What you could do, it write a constructor, in which you will put your initialization. Like this

1
2
3
4
5
6
7
8
9
10
11
12
class Maze{
public:
	static const int rows = 10;
	static const int columns = 12;
	int MazeArray[rows][columns]; 

        Maze() {
            MazeArray[0][0] = 1; 
            MazeArray[0][1] = 1;
            // .....
            // I know it's boring and long ...
        }


I don't think there is another way. Of course could set everything to 0 or 1 with a simple loop !

Does that make sens ?
Yes it makes :) , Thanks so Much
Topic archived. No new replies allowed.