我正在尝试生成一个 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/