How do I initialize an array in a C ++ constructor?

  • 0
    In general, I'm a weber and you don't need to scold me much))
    I just decided to remember the syntax.
    class Map{
    private:
    	int x;
    	int y;
    	int map[20][20];
    
    public:
    	Map(){
    		this->map = {
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
    			{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
    		};
    	}
    };

    How can I properly initialize the array in the constructor?
    Thank you.
    C++ Lukas Kerr, Jun 20, 2019

  • 1 Answers
  • 0
    In this particular case, initialization with zeros can be done like this:

    memset (map, 0, sizeof (map));


    If map is an array of POD objects and initialization is non-trivial, you can copy the reference array using memcpy:
    Map(){
    static const map_init[20][20] = {
    ...
    };
    memcpy(map, map_init, sizeof(map));
    }



    Otherwise - in any other "object" way - std :: copy, loop, whatever.


    Starting from C ++ 11, you can initialize an array in the constructor initialization list, regardless of whether the POD is a field or not, for example:
    Map(): map{{1, 2, 3, 4, 5, ...}, {21, 22, 23, 24, 25, ...}, ...} {
    }
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!