I define a 2D array in my header file
char map[3][3];
How can I initialize the values in the class constructor like this
map = {{'x', 'x', 'o'},
{'o', 'o', 'x'},
{'x', 'o', 'x'}};
I define a 2D array in my header file
char map[3][3];
How can I initialize the values in the class constructor like this
map = {{'x', 'x', 'o'},
{'o', 'o', 'x'},
{'x', 'o', 'x'}};
memcpy(map,"xxoooxxox",9);
or
char tmp[3][3] =
{{'x','x','o'},
{'o','o','x'},
{'x','o','x'}};
memcpy(map,tmp,9);
Firstly, there is a difference between assignment and initialization. The OP title is about initialization.
Secondly, you have not told us if your 2D array is a class member(static/non static) or a namespace variable.
-Since you mentioned about initializing it in the class constructor, I am assuming that it is a class non static member, because:
$12.6.2/2 - "Unless the mem-initializer-id names the constructor’s class, a non-static data member of the constructor’s class, or a direct or virtual base of that class, the mem-initializer is ill-formed."
Further, as of C++03 the member array cannot be initialized in the constructor initializer list for the case in OP(not sure about C++0x) though.
-If your 2D array is a static member of your class, you should initialize it as you did (with a slight change), but not in the constructor. This should be done in the enclosing namespace scope once and only once in any of the translation units.
char (A::map)[3][3] = {{'x', 'x', 'o'},
{'o', 'o', 'x'},
{'x', 'o', 'x'}};
-Alternatively, if your 2D array is a namespace scope variable, the definition of the array should be taken out of the header file (unless it is also static) as it will cause a redefinition error and be defined and initialized once and only once in any translation unit as
char map[3][3] = {{'x', 'x', 'o'},
{'o', 'o', 'x'},
{'x', 'o', 'x'}};