Creating an 2-dimensional array of a struct results in crash

后端 未结 4 1035
抹茶落季
抹茶落季 2021-01-07 01:14

I am trying to generate a two-dimensional array of a struct, but this results in the program not launching. The window freezes and the program quits after a few

4条回答
  •  死守一世寂寞
    2021-01-07 01:15

    You are allocating 801 * 401 (=321201) elements of struct absCell on the stack. Assuming you have a 32bit machine it is 2569608 Byte (~2.45 MB). According to this it is blowing up your stack.

    Move the elements to heap like:

    class Field {
    public:
        static const int minX = -400;
        static const int maxX = 400;
        static const int minY = 0;
        static const int maxY = 400;
    
        Field() {
            cells = new absCell*[maxX - minX + 1];
            for(int i=0; i

    Update

    Material and health can be saved in a char. Accessing health you have to recalculate it:

    put -> x*100
    get -> x/100
    

    Update 2

    Except you have some reasons, using a vector is most likely the better option, as Mark B 's answer describes.

提交回复
热议问题