我有一个编程作业,需要存储多达100个大小高达500*500的char二维数组,以及与每个数组相关的4个数字.它应该是这样的:
struct BLOCK {
short x1;
short y1;
short x2;
short y2;
char points [ 500 ] [ 500 ];
};
Run Code Online (Sandbox Code Playgroud)
该程序必须读取这样的输入:
p
identifier_1 x1 y1 x2 y2
...
identifier_p x1 y1 x2 y2
Run Code Online (Sandbox Code Playgroud)
哪里
当我尝试输入p> 9时,我尝试使其工作失败:
#include <iostream>
#include <string>
using namespace std;
struct BLOCK {
short x1;
short y1;
short x2;
short y2;
char points [ 500 ] [ 500 ];
};
int main () {
short numberOfBlocks;
cin >> numberOfBlocks;
short indices [ numberOfBlocks ];
BLOCK BLOCKsTable [ numberOfBlocks ];
}
Run Code Online (Sandbox Code Playgroud)
我也注意到,这件事不起作用:
char array [ 100 ] [ 500 ] [ 500 ];
Run Code Online (Sandbox Code Playgroud)
我只能使用:
我不能用
我的问题:
500 * 500 = 250000。按整数计算,每个实例BLOCK将占用大约 250kb。
您的示例代码使用 gcc 扩展来实例化堆栈上最多包含n实例的数组。BLOCK因此,十个实例将占用大约 2.5 MB。我不认为这是一个问题,但也许您实验室的 Linux 机器配置了每个进程堆栈大小的较小最大值。无论如何,100 个实例BLOCK预计将占用堆栈上的 20.5 MB 空间,这更有可能耗尽每个进程的堆栈分配,因此这在任何情况下都不起作用。
“如何能够声明最多 100 个结构体 BLOCK?”问题的答案 就是简单地在全局静态命名空间中声明它们,而不是在堆栈上。您的作业条件非常谨慎,它们似乎是为了迫使您了解各种类型的实例化对象之间的差异——堆、堆栈和静态/全局。