【发布时间】:2017-06-28 07:48:06
【问题描述】:
当我在下面的代码中调用我的 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;
}
请帮忙,提前致谢!
编辑:我的问题不在于数组的大小,正如我在 cmets 中提到的那样。当它们被放置在结构之外时,我能够制作数组并运行代码。
【问题讨论】:
-
stdio.h、stdlib.h和string.h是 C 标准库,而不是 C++ 标准库。 C++ 标准库头文件永远不会有后缀.h。using namespace std;is a bad practice。此外,初始化类成员的现代 C++ 方法是member list initialization。 -
您认为
long long tree [1<<20], arr [1<<20];会占用多少内存?具有自动存储期限?你的调用栈有多大? -
long long tree [1<<20], arr [1<<20];在堆栈上变得相当大。很可能溢出。我建议改用std::vector<long long> tree (1<<20), arr (1<<20);。 -
@tambre:我的 C++ 标准副本指定
stdio.h等的细节与cstdio完全相同。它们在什么意义上“不是 C++ 标准库”? (请注意,在实践中,cstdio始终将名称与std::一样放在全局命名空间中,现在标准允许这样做。)