当我在下面的代码中为我的 SegTree 结构调用构造函数时,我一直得到一个非零退出代码。当我注释掉初始化结构的行时,程序运行没有问题。有人可以解释为什么会发生这种情况以及如何修复我的代码吗?
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <string>
#include <vector>
#include <string.h>
using namespace std;
struct SegTree{
int N;
long long tree [1<<20], arr [1<<20];
SegTree(int x){ N = x; }
};
int main(){
SegTree st(len);
return 0;
}
请帮忙,提前致谢!
编辑:正如我在评论中提到的那样,我的问题不是数组的大小。当它们被放置在结构之外时,我能够制作数组并运行代码。
最佳答案
哇。这是一个大结构:
struct SegTree{
int N;
long long tree [1<<20], arr [1<<20];
1<<20
是 1 兆。 long long
通常是 8 个字节,所以您的结构是 16 MB ...并且您在堆栈上分配它。通常,程序会为堆栈分配 1MB 空间……所以它放不下!
解决方案是将数组更改为 vector 。然后该数组将分配到堆上,您应该没问题:
std::vector<long long> tree = {1<<20};
std::vector<long long> arr = {1<<20};
(一旦您使用 vector ,您可能会比在构造函数中以某个最大大小一次分配所有内存做得更好)。
关于c++ - C++ 中结构的构造函数导致非零退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44796537/