c++ - 创建结构的二维数组会导致崩溃

标签 c++ arrays struct

我正在尝试生成一个 struct 的二维数组,但这导致程序无法启动。窗口卡住,程序在几秒钟后退出。知道为什么吗?

这是我尝试定义数组 cells 的文件。

#ifndef _FIELD_H_
    #define _FIELD_H_

class Field {
    public:
        static const int minX = -400;
        static const int maxX = 400;
        static const int minY = 0;
        static const int maxY = 400;

        Field();

    private:
        struct absCell {
            int material;
            float health;
        } cells[maxX - minX + 1][maxY - minY + 1];
};

#endif

去掉这四行程序就可以运行了:

        struct absCell {
            int material;
            float health;
        } cells[maxX - minX + 1][maxY - minY + 1];

知道这是怎么发生的吗?感谢您的帮助!

更新

好吧,显然问题在于这个数组变得相当大。也许你可以帮我优化一下。

Material 必须是 0 到 10 之间的整数。 生命值必须是 0 到 1 之间的 float ,最多 2 位小数。

如何限制这些变量的大小?

更新2

Mark B 建议使用 vector ,而 itwasntpete 建议使用指针、new 和 delete。这两种方法的区别在哪里,优缺点是什么?再次感谢!

最佳答案

您正在堆栈上分配 struct absCell 的 801 * 401 (=321201) 个元素。假设您有一台 32 位机器,它是 2569608 字节(~2.45 MB)。根据this它正在炸毁你的筹码。

将元素移动到堆中:

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;
};

更新

Material 和生命值可以保存在 char 中。访问健康你必须重新计算它:

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

更新2

除非您有某些原因,否则使用 vector 很可能是更好的选择,如 Mark B 的 answer描述。

关于c++ - 创建结构的二维数组会导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18923339/

相关文章:

c++ - 结构体的 sizeof 会受到数组元数据的影响吗?

c++ - 将 NULL 转换为 long 是不是有歧义?

c++ - 构造对象和调用成员函数

javascript - 如何在 JavaScript 中用数字填充表格?

javascript - 如何使用纯 JavaScript 访问最内层的双重嵌套数组/对象?

c - 为什么要将空结构创建为新的 typedef 并将其用作指针类型?

c++ - 是否可以更改 ostringstream rdbuf?

c++ - Mujoco : Missing shared libraries with Simulate. cpp 入门步骤

JavaScript 如何从数组中获取所有字符串并使用过滤器打印它们?

json - 将 JSON 对象中的两个值连接到 Go 中的 map[string]bool