简体   繁体   English

C ++中的结构构造函数导致非零退出代码

[英]Constructor of a Struct in C++ Causes Non-Zero Exit Code

When I call the constructor for my SegTree struct in the code below, I keep getting a non-zero exit code. 当我在下面的代码中为我的SegTree结构调用构造函数时,我不断得到一个非零的退出代码。 When I comment out the line that initializes the struct, the program runs with no issue. 当我注释掉初始化结构的那一行时,程序运行没有问题。 Can someone explain why this is happening and how to fix my code? 有人可以解释为什么会这样以及如何修复我的代码吗?

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

Please help, and thanks in advance! 请帮助,并在此先感谢!

EDIT: My issue is not the size of the arrays, as I have mentioned in the comments. 编辑:我的问题不是数组的大小,正如我在评论中提到的那样。 I am able to make the arrays and run the code when they are placed outside the struct. 当它们放置在结构外部时,我能够制作数组并运行代码。

Wow. 哇。 That's a big structure: 这是一个很大的结构:

struct SegTree{
    int N;
    long long tree [1<<20], arr [1<<20];

1<<20 is 1 Meg. 1<<20是1兆欧。 long long is typically 8 bytes, so your structure is 16 Mbytes ... and you are allocating it on the stack. long long通常是8个字节,因此您的结构是16 MB ...并且您正在将其分配在堆栈上。 Typically, programs allocate 1Mbyte for the stack ... so it won't fit! 通常,程序会为堆栈分配1Mbyte的内存,因此不适合!

The solution is to change the arrays into vectors. 解决方案是将数组更改为向量。 The array will then be allocated on the heap, and you should be fine: 然后将在堆上分配该数组,您应该可以:

    std::vector<long long> tree = {1<<20};
    std::vector<long long> arr  = {1<<20};

(once you are using vectors, you may well be able to do much better than allocating the memory all at once at some maximum size in the constructor). (一旦使用向量,您可能会比在构造函数中以某个最大大小一次分配所有内存更好地做得多)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM