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

后端 未结 4 1003
抹茶落季
抹茶落季 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<maxX - minX + 1; i++)
                cells[i] = new absCell[maxY - minY + 1];
        }
    
        ~Field() {
            for(int i=0; i<maxX - minX + 1; i++)
                delete[] cells[i];
    
            delete[] cells;
        }
    
    private:
        struct absCell {
            unsigned char material;
            unsigned char health;
        }**cells;
    };
    

    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.

    0 讨论(0)
  • 2021-01-07 01:17

    My guess is you're hitting the stack limit. When you make that array like it is its trying to put 801*401*8 bytes on your stack. I did a quick compile and was having crashes until I lowered the numbers for your various mins and maxes.

    0 讨论(0)
  • 2021-01-07 01:28

    Based on update note:

    The first thing you can do is easily optimize your struct for space by using unsigned char for each attribute, using a fixed-point representation for your existing float (for example 0.23 would be stored as the integer 23).

    Then store the structs on the heap with vector instead of an array:

        struct absCell {
            unsigned char material;
            unsigned char health;
        };
        std::vector<std::vector<absCell> > cells_;
    

    Then set up the constructor:

    Field() : cells_(maxX - minX + 1, std::vector<absCell>(maxY - minY + 1)) {}
    
    0 讨论(0)
  • 2021-01-07 01:31

    If I got your snippet right way, you're trying to create an array. Allocation of the array is stack-based, with more than 2 Mb size required. There may be a chance that your stack has less than that 2Mb available, thus the code crashes right at the moment you're entering the function.

    Try to allocate the same array dinamically.

    0 讨论(0)
提交回复
热议问题