简体   繁体   English

如何初始化一个很长的数组?

[英]How to initialize a very long array?

I am just trying to initialize a huge array.我只是想初始化一个巨大的数组。 My code is given below:我的代码如下:

#include<iostream>
using namespace std;

int main()
{
    int T;
    cin >> T;
    while (T--) 
    {
        int d;
        cin >> d;
        int arr[d + 1];
        for (int i = 0; i <= d; i++)
            arr[i] = 0;
    }
    return 0;
}

Now when I input现在当我输入

1 502334160

then I got error Runtime Error - SIGSEGV .然后我得到了错误Runtime Error - SIGSEGV

I want to know how to initialize this type of array.我想知道如何初始化这种类型的数组。

The array may be too big to fit in your program's stack address space.该数组可能太大而无法放入程序的堆栈地址空间。 If you allocate the array on the heap you should be fine.如果你在堆上分配数组,你应该没问题。

int* arr = new int[d + 1];

But remember that this will require you to delete[] the array.但请记住,这将要求您delete[]数组。 A better solution would be to use std::vector<int> and resize it to d + 1 elements.更好的解决方案是使用std::vector<int>并将其调整d + 1元素。

First: Variable length arrays (VLA) are illegal in C++.第一:可变长度数组 (VLA) 在 C++ 中是非法的。 It might be an extension (as it is in gcc), but it won't build on all compilers.它可能是一个扩展(就像在 gcc 中一样),但它不会构建在所有编译器上。

Second: You can initialize an array with brace initialization.第二:您可以使用大括号初始化来初始化数组。 If you don't specify all elements, the others will get default value of 0 (in case of int ).如果您不指定所有元素,则其他元素将获得默认值 0(在int情况下)。 So:所以:

int arr[SIZE] {} //specify 0 elements -> all initialized to value 0

Third thing: you allocate your array on stack, so when you create an array of length 1502334160 than it's stack overflow.第三件事:你在堆栈上分配你的数组,所以当你创建一个长度为1502334160的数组时,它不是堆栈溢出。 This amount of ints (assuming 4 bytes each) is almost 6GB of memory while stack is usually 1-2MB.这个整数数量(假设每个 4 个字节)几乎是 6GB 的内存,而堆栈通常是 1-2MB。

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

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