C++ 中是否有最大数组长度限制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/216259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:47:31  来源:igfitidea点击:

Is there a max array length limit in C++?

c++arrays

提问by luiss

Is there a max length for an array in C++?

C++ 中的数组是否有最大长度?

Is it a C++ limit or does it depend on my machine? Is it tweakable? Does it depend on the type the array is made of?

它是 C++ 限制还是取决于我的机器?可以调整吗?它是否取决于数组的类型?

Can I break that limit somehow or do I have to search for a better way of storing information? And what should be the simplest way?

我可以以某种方式打破这个限制,还是必须寻找更好的信息存储方式?最简单的方法应该是什么?

What I have to do is storing long long int on an array, I'm working in a Linux environment. My question is: what do I have to do if I need to store an array of N long long integers with N > 10 digits?

我要做的是将 long long int 存储在一个数组上,我在 Linux 环境中工作。我的问题是:如果我需要存储 N > 10 位的 N 个长整数数组,我该怎么办?

I need this because I'm writing some cryptographic algorithm (as for example the p-Pollard) for school, and hit this wall of integers and length of arrays representation.

我需要这个,因为我正在为学校编写一些加密算法(例如 p-Pollard),并撞上了这堵整数和数组长度表示的墙。

采纳答案by Konrad Rudolph

There are two limits, both not enforced by C++ but rather by the hardware.

有两个限制,都不是由 C++ 强制执行的,而是由硬件强制执行的。

The first limit (should never be reached) is set by the restrictions of the size type used to describe an index in the array (and the size thereof). It is given by the maximum value the system's std::size_tcan take. This data type is large enough to contain the size in bytes of any object

第一个限制(不应达到)由用于描述数组中索引(及其大小)的大小类型的限制设置。它由系统std::size_t可以采用的最大值给出。此数据类型足够大,可以包含任何对象的字节大小

The other limit is a physical memory limit. The larger your objects in the array are, the sooner this limit is reached because memory is full. For example, a vector<int>of a given size ntypically takes multiple times as much memory as an array of type vector<char>(minus a small constant value), since intis usually bigger than char. Therefore, a vector<char>may contain more items than a vector<int>before memory is full. The same counts for raw C-style arrays like int[]and char[].

另一个限制是物理内存限制。数组中的对象越大,越快达到此限制,因为内存已满。例如,vector<int>给定大小n 的 a通常需要多倍于类型数组的内存vector<char>(减去一个小的常量值),因为int通常大于char。因此,在内存已满之前,avector<char>可能包含比 a 多的项目vector<int>。原始 C 样式数组(如int[]和 )的计数相同char[]

Additionally, this upper limit may be influenced by the type of allocatorused to construct the vectorbecause an allocatoris free to manage memory any way it wants. A very odd but nontheless conceivable allocator could pool memory in such a way that identical instances of an object share resources. This way, you could insert a lot of identical objects into a container that would otherwise use up all the available memory.

此外,这个上限可能会受到allocator用于构造的类型的影响,vector因为它allocator可以自由地以任何它想要的方式管理内存。一个非常奇怪但仍然可以想象的分配器可以通过对象的相同实例共享资源的方式来池化内存。这样,您可以将许多相同的对象插入到容器中,否则这些对象将耗尽所有可用内存。

Apart from that, C++ doesn't enforce any limits.

除此之外,C++ 不强制执行任何限制。

回答by Martin York

Nobody mentioned the limit on the size of the stack frame.

没有人提到堆栈帧大小的限制。

There are two places memory can be allocated:

有两个地方可以分配内存:

  • On the heap (dynamically allocated memory).
    The size limit here is a combination of available hardware and the OS's ability to simulate space by using other devices to temporarily store unused data (i.e.move pages to hard disk).
  • On the stack (Locally declared variables).
    The size limit here is compiler defined (with possible hardware limits). If you read the compiler documentation you can often tweak this size.
  • 在堆上(动态分配的内存)。
    这里的大小限制是可用硬件和操作系统通过使用其他设备来临时存储未使用的数据(即,将页面移动到硬盘)来模拟空间的能力的组合。
  • 在堆栈上(本地声明的变量)。
    这里的大小限制是编译器定义的(可能有硬件限制)。如果您阅读编译器文档,您通常可以调整此大小。

Thus if you allocate an array dynamically (the limit is large and described in detail by other posts.

因此,如果你动态分配一个数组(限制很大,其他帖子有详细描述。

int* a1 = new int[SIZE];  // SIZE limited only by OS/Hardware

Alternatively if the array is allocated on the stack then you are limited by the size of the stack frame. N.B.vectors and other containers have a small presence in the stack but usually the bulk of the data will be on the heap.

或者,如果数组是在堆栈上分配的,那么您将受到堆栈帧大小的限制。NB向量和其他容器在堆栈中的存在很小,但通常大部分数据将在堆上。

int a2[SIZE]; // SIZE limited by COMPILER to the size of the stack frame

回答by SmacL

Looking at it from a practical rather than theoretical standpoint, on a 32 bit Windows system, the maximum total amount of memory available for a single process is 2 GB. You can break the limit by going to a 64 bit operating system with much more physical memory, but whether to do this or look for alternatives depends very much on your intended users and their budgets. You can also extend it somewhat using PAE.

从实际而非理论的角度来看,在 32 位 Windows 系统上,单个进程可用的最大内存总量为 2 GB。您可以通过使用具有更多物理内存的 64 位操作系统来打破限制,但是是这样做还是寻找替代方案在很大程度上取决于您的目标用户及其预算。您也可以使用PAE稍微扩展它。

The type of the array is very important, as default structure alignment on many compilers is 8 bytes, which is very wasteful if memory usage is an issue. If you are using Visual C++ to target Windows, check out the #pragma packdirective as a way of overcoming this.

数组的类型非常重要,因为许多编译器的默认结构对齐是 8 字节,如果内存使用有问题,这非常浪费。如果您使用 Visual C++ 来定位 Windows,请查看#pragma pack指令作为克服此问题的一种方式。

Another thing to do is look at what in memory compression techniques might help you, such as sparse matrices, on the fly compression, etc... Again this is highly application dependent. If you edit your post to give some more information as to what is actually in your arrays, you might get more useful answers.

要做的另一件事是查看内存压缩技术可能对您有帮助的内容,例如稀疏矩阵、动态压缩等……这又是高度依赖于应用程序的。如果您编辑帖子以提供有关数组中实际内容的更多信息,您可能会得到更有用的答案。

Edit: Given a bit more information on your exact requirements, your storage needs appear to be between 7.6 GB and 76 GB uncompressed, which would require a rather expensive 64 bit box to store as an array in memory in C++. It raises the question why do you want to store the data in memory, where one presumes for speed of access, and to allow random access. The best way to store this data outside of an array is pretty much based on how you want to access it. If you need to access array members randomly, for most applications there tend to be ways of grouping clumps of data that tend to get accessed at the same time. For example, in large GIS and spatial databases, data often gets tiled by geographic area. In C++ programming terms you can override the [] array operator to fetch portions of your data from external storage as required.

编辑:提供有关您的确切要求的更多信息,您的存储需求似乎在未压缩的 7.6 GB 到 76 GB 之间,这将需要一个相当昂贵的 64 位盒子在 C++ 中作为数组存储在内存中。它提出了一个问题,为什么要将数据存储在内存中,假设访问速度,并允许随机访问。将这些数据存储在数组之外的最佳方式很大程度上取决于您希望如何访问它。如果您需要随机访问数组成员,对于大多数应用程序,往往有方法将倾向于同时访问的数据块分组。例如,在大型 GIS 和空间数据库中,数据通常按地理区域进行平铺。在 C++ 编程术语中,您可以覆盖 [] 数组运算符以根据需要从外部存储中获取部分数据。

回答by Tarski

I would agree with the above, that if you're intializing your array with

我同意上面的说法,如果你正在初始化你的数组

 int myArray[SIZE] 

then SIZE is limited by the size of an integer. But you can always malloc a chunk of memory and have a pointer to it, as big as you want so long as malloc doesnt return NULL.

那么 SIZE 受整数大小的限制。但是你总是可以 malloc 一块内存并有一个指向它的指针,只要 malloc 不返回 NULL 就可以。

回答by Artur Opalinski

To summarize the responses, extend them, and to answer your question directly:

No, C++ does not impose any limits for the dimensionsof an array.

But as the array has to be stored somewhere in memory, so memory-related limits imposed by other parts of the computer system apply. Note that these limits do not directly relate to the dimensions(=number of elements) of the array, but rather to its size(=amount of memory taken). Dimensions (D) and in-memory size (S) of an array is not the same, as they are related by memory taken by a single element (E): S=D* E.

Now Edepends on:

总结回答,扩展它们,并直接回答您的问题:

不,C++ 不对数组的维数施加任何限制。

但是由于数组必须存储在内存中的某个位置,因此计算机系统其他部分施加的与内存相关的限制也适用。请注意,这些限制与数组的维度(=元素数量)没有直接关系,而是与数组大小(=占用的内存量)相关。数组的维度 ( D) 和内存中的大小 ( S) 不同,因为它们与单个元素 ( E)占用的内存相关:S= D* E

现在E取决于:

  • the type of the array elements (elements can be smaller or bigger)
  • memory alignment (to increase performance, elements are placed at addresses which are multiplies of some value, which introduces
    ‘wasted space' (padding) between elements
  • size of static parts of objects (in object-oriented programming static components of objects of the same type are only stored once, independent from the number of such same-type objects)
  • 数组元素的类型(元素可以更小或更大)
  • 内存对齐(为了提高性能,元素被放置在某个值的倍数的地址处,这会
    在元素之间引入“浪费空间”(填充)
  • 对象静态部分的大小(在面向对象编程中,同类型对象的静态组件只存储一次,与此类同类型对象的数量无关)

Also note that you generally get different memory-related limitations by allocating the array data on stack (as an automatic variable: int t[N]), or on heap (dynamic alocation with malloc()/newor using STL mechanisms), or in the static part of process memory (as a static variable: static int t[N]). Even when allocating on heap, you still need some tiny amount of memory on stack to store references to the heap-allocated blocks of memory (but this is negligible, usually).

The size of size_ttype has no influence on the programmer (I assume programmer uses size_ttype for indexing, as it is designed for it), as compiler provider has to typedefit to an integer type big enough to address maximal amount of memory possible for the given platform architecture.

The sources of the memory-size limitations stem from

另请注意,通过在堆栈(作为自动变量int t[N]:)或堆(使用malloc()/new或使用 STL 机制的动态分配)或进程内存的静态部分(如一个静态变量:)static int t[N]。即使在堆上分配时,堆栈上仍然需要少量内存来存储对堆分配的内存块的引用(但这通常可以忽略不计)。类型

的大小对size_t程序员没有影响(我假设程序员使用size_t类型进行索引,因为它是为它设计的),因为编译器提供者必须将typedef它设置为一个足够大的整数类型,以解决给定平台可能的最大内存量建筑学。

内存大小限制的来源源于

  • amount of memory available to the process (which is limited to 2^32 bytes for 32-bit applications, even on 64-bits OS kernels),
  • the division of process memory (e.g. amount of the process memory designed for stack or heap),
  • the fragmentation of physical memory (many scattered small free memory fragments are not applicable to storing one monolithic structure),
  • amount of physical memory,
  • and the amount of virtual memory.
  • 进程可用的内存量(对于 32 位应用程序,限制为 2^32 字节,即使在 64 位操作系统内核上),
  • 进程内存的划分(例如为堆栈或堆设计的进程内存量),
  • 物理内存碎片化(很多零散的小空闲内存碎片不适用于存储一个单体结构),
  • 物理内存量,
  • 和虚拟内存量。

They can not be ‘tweaked' at the application level, but you are free to use a different compiler (to change stack size limits), or port your application to 64-bits, or port it to another OS, or change the physical/virtual memory configuration of the (virtual? physical?) machine.

It is not uncommon (and even advisable) to treat all the above factors as external disturbances and thus as possible sources of runtime errors, and to carefully check&react to memory-allocation related errors in your program code.

So finally: while C++ does not impose any limits, you still have to check for adverse memory-related conditions when running your code... :-)

它们不能在应用程序级别“调整”,但您可以自由使用不同的编译器(更改堆栈大小限制),或将您的应用程序移植到 64 位,或将其移植到另一个操作系统,或更改物理/ (虚拟?物理?)机器的虚拟内存配置。

将上述所有因素视为外部干扰并因此视为运行时错误的可能来源,并仔细检查和应对程序代码中与内存分配相关的错误并不少见(甚至建议)。

所以最后:虽然 C++ 没有强加任何限制,但在运行代码时,您仍然必须检查与内存相关的不利条件...... :-)

回答by Dmitry Torba

As many excellent answers noted, there are a lot of limits that depend on your version of C++ compiler, operating system and computer characteristics. However, I suggest the following script on Python that checks the limit on your machine.

正如许多优秀答案所指出的那样,有很多限制取决于您的 C++ 编译器版本、操作系统和计算机特性。但是,我建议在 Python 上使用以下脚本来检查您机器上的限制。

It uses binary search and on each iteration checks if the middle size is possible by creating a code that attempts to create an array of the size. The script tries to compile it (sorry, this part works only on Linux) and adjust binary search depending on the success. Check it out:

它使用二进制搜索,并在每次迭代中通过创建尝试创建大小数组的代码来检查是否可以使用中间大小。该脚本尝试编译它(抱歉,这部分仅适用于 Linux)并根据成功调整二进制搜索。一探究竟:

import os

cpp_source = 'int a[{}]; int main() {{ return 0; }}'

def check_if_array_size_compiles(size):
        #  Write to file 1.cpp
        f = open(name='1.cpp', mode='w')
        f.write(cpp_source.format(m))
        f.close()
        #  Attempt to compile
        os.system('g++ 1.cpp 2> errors')
        #  Read the errors files
        errors = open('errors', 'r').read()
        #  Return if there is no errors
        return len(errors) == 0

#  Make a binary search. Try to create array with size m and
#  adjust the r and l border depending on wheather we succeeded
#  or not
l = 0
r = 10 ** 50
while r - l > 1:
        m = (r + l) // 2
        if check_if_array_size_compiles(m):
                l = m
        else:
                r = m

answer = l + check_if_array_size_compiles(r)
print '{} is the maximum avaliable length'.format(answer)

You can save it to your machine and launch it, and it will print the maximum size you can create. For my machine it is 2305843009213693951.

您可以将其保存到您的机器并启动它,它将打印您可以创建的最大尺寸。对于我的机器,它是 2305843009213693951。

回答by Rob Wells

One thing I don't think has been mentioned in the previous answers.

我认为之前的答案中没有提到的一件事。

I'm always sensing a "bad smell" in the refactoring sense when people are using such things in their design.

当人们在他们的设计中使用这些东西时,我总是感觉到重构意义上的“难闻的气味”。

That's a huge array and possibly not the best way to represent your data both from an efficiency point of view and a performance point of view.

这是一个庞大的数组,从效率和性能的角度来看,这可能不是表示数据的最佳方式。

cheers,

干杯,

Rob

回答by Jay

If you have to deal with data that large you'll need to split it up into manageable chunks. It won't all fit into memory on any small computer. You can probably load a portion of the data from disk (whatever reasonably fits), perform your calculations and changes to it, store it to disk, then repeat until complete.

如果您必须处理如此大的数据,则需要将其拆分为可管理的块。它不会全部放入任何小型计算机的内存中。您可能可以从磁盘加载一部分数据(只要合适),执行计算并对其进行更改,将其存储到磁盘,然后重复直到完成。

回答by kayleeFrye_onDeck

As annoyingly non-specific as all the current answers are, they're mostly right but with many caveats, not always mentioned. The gist is, you have two upper-limits, and only one of them is something actually defined, so YMMV:

与当前所有答案一样令人讨厌的非特定性,它们大多是正确的,但有许多警告,并不总是被提及。要点是,你有两个上限,其中只有一个是实际定义的,所以YMMV

1. Compile-time limits

1. 编译时间限制

Basically, what your compiler will allow. For Visual C++ 2017 on an x64 Windows 10 box, this is my max limit at compile-time before incurring the 2GB limit,

基本上,您的编译器将允许的内容。对于 x64 Windows 10 机器上的 Visual C++ 2017,这是我在编译时达到 2GB 限制之前的最大限制,

unsigned __int64 max_ints[255999996]{0};

If I did this instead,

如果我这样做,

unsigned __int64 max_ints[255999997]{0};

I'd get:

我会得到:

Error C1126 automatic allocation exceeds 2G

Error C1126 automatic allocation exceeds 2G

I'm not sure how 2G correllates to 255999996/7. I googled both numbers, and the only thing I could find that was possibly related was this *nix Q&A about a precision issue with dc. Either way, it doesn't appear to matter which type of int array you're trying to fill, just how many elements can be allocated.

我不确定 2G 与255999996/ 的关系7。我GOOGLE了两个号码,我能找到的唯一的事情这是可能相关的是这样的* nix的Q&A关于精度问题dc。无论哪种方式,您尝试填充哪种类型的 int 数组似乎都无关紧要,只需分配多少元素即可。

2. Run-time limits

2. 运行时间限制

Your stack and heap have their own limitations. These limits are both values that change based on available system resources, as well as how "heavy" your app itself is. For example, with my current system resources, I can get this to run:

您的堆栈和堆有其自身的局限性。这些限制都是根据可用系统资源以及您的应用程序本身的“重”程度而变化的值。例如,使用我当前的系统资源,我可以让它运行:

int main()
{
    int max_ints[257400]{ 0 };
    return 0;
}

But if I tweak it just a little bit...

但是如果我稍微调整一下......

int main()
{
    int max_ints[257500]{ 0 };
    return 0;
}

Bam! Stack overflow!

砰!堆栈溢出!

Exception thrown at 0x00007FF7DC6B1B38 in memchk.exe: 0xC00000FD:Stack overflow (parameters: 0x0000000000000001, 0x000000AA8DE03000).Unhandled exception at 0x00007FF7DC6B1B38 in memchk.exe: 0xC00000FD:Stack overflow (parameters: 0x0000000000000001, 0x000000AA8DE03000).

Exception thrown at 0x00007FF7DC6B1B38 in memchk.exe: 0xC00000FD:Stack overflow (parameters: 0x0000000000000001, 0x000000AA8DE03000).Unhandled exception at 0x00007FF7DC6B1B38 in memchk.exe: 0xC00000FD:Stack overflow (parameters: 0x0000000000000001, 0x000000AA8DE03000).

And just to detail the whole heaviness of your app point, this was good to go:

只是为了详细说明您的应用程序点的整体重量,这很好:

int main()
{
    int maxish_ints[257000]{ 0 };
    int more_ints[400]{ 0 };
    return 0;
}  

But this caused a stack overflow:

但这导致了堆栈溢出:

int main()
{
    int maxish_ints[257000]{ 0 };
    int more_ints[500]{ 0 };
    return 0;
}  

回答by Joseph Wood

I'm surprised the max_size()member function of std::vectorhas not been mentioned here.

我很惊讶这里没有提到std::vectormax_size()成员函数。

"Returns the maximum number of elements the container is able to hold due to system or library implementation limitations, i.e. std::distance(begin(), end()) for the largest container."

“由于系统或库实现限制,返回容器能够容纳的最大元素数,即最大容器的 std::distance(begin(), end())。”

We know that std::vectoris implemented as a dynamic array underneath the hood, so max_size()should give a very close approximation of the maximum length of a dynamicarray on your machine.

我们知道这std::vector是作为引擎盖下的动态数组实现的,因此max_size()应该非常接近您机器上动态数组的最大长度。

The following program builds a table of approximate maximum array length for various data types.

以下程序为各种数据类型构建了一个近似最大数组长度的表。

#include <iostream>
#include <vector>
#include <string>
#include <limits>

template <typename T>
std::string mx(T e) {
    std::vector<T> v;
    return std::to_string(v.max_size());
}

std::size_t maxColWidth(std::vector<std::string> v) {
    std::size_t maxWidth = 0;

    for (const auto &s: v)
        if (s.length() > maxWidth)
            maxWidth = s.length();

    // Add 2 for space on each side
    return maxWidth + 2;
}

constexpr long double maxStdSize_t = std::numeric_limits<std::size_t>::max();

// cs stands for compared to std::size_t
template <typename T>
std::string cs(T e) {
    std::vector<T> v;
    long double maxSize = v.max_size();
    long double quotient = maxStdSize_t / maxSize;
    return std::to_string(quotient);
}

int main() {
    bool v0 = 0;
    char v1 = 0;

    int8_t v2 = 0;
    int16_t v3 = 0;
    int32_t v4 = 0;
    int64_t v5 = 0;

    uint8_t v6 = 0;
    uint16_t v7 = 0;
    uint32_t v8 = 0;
    uint64_t v9 = 0;

    std::size_t v10 = 0;
    double v11 = 0;
    long double v12 = 0;

    std::vector<std::string> types = {"data types", "bool", "char", "int8_t", "int16_t",
                                      "int32_t", "int64_t", "uint8_t", "uint16_t",
                                      "uint32_t", "uint64_t", "size_t", "double",
                                      "long double"};

    std::vector<std::string> sizes = {"approx max array length", mx(v0), mx(v1), mx(v2),
                                      mx(v3), mx(v4), mx(v5), mx(v6), mx(v7), mx(v8),
                                      mx(v9), mx(v10), mx(v11), mx(v12)};

    std::vector<std::string> quotients = {"max std::size_t / max array size", cs(v0),
                                          cs(v1), cs(v2), cs(v3), cs(v4), cs(v5), cs(v6),
                                          cs(v7), cs(v8), cs(v9), cs(v10), cs(v11), cs(v12)};

    std::size_t max1 = maxColWidth(types);
    std::size_t max2 = maxColWidth(sizes);
    std::size_t max3 = maxColWidth(quotients);

    for (std::size_t i = 0; i < types.size(); ++i) {
        while (types[i].length() < (max1 - 1)) {
            types[i] = " " + types[i];
        }

        types[i] += " ";

        for  (int j = 0; sizes[i].length() < max2; ++j)
            sizes[i] = (j % 2 == 0) ? " " + sizes[i] : sizes[i] + " ";

        for  (int j = 0; quotients[i].length() < max3; ++j)
            quotients[i] = (j % 2 == 0) ? " " + quotients[i] : quotients[i] + " ";

        std::cout << "|" << types[i] << "|" << sizes[i] << "|" << quotients[i] << "|\n";
    }

    std::cout << std::endl;

    std::cout << "N.B. max std::size_t is: " <<
        std::numeric_limits<std::size_t>::max() << std::endl;

    return 0;
}

On my macOS (clang version 5.0.1), I get the following:

在我的 macOS(clang 版本 5.0.1)上,我得到以下信息:

|  data types | approx max array length | max std::size_t / max array size |
|        bool |   9223372036854775807   |             2.000000             |
|        char |   9223372036854775807   |             2.000000             |
|      int8_t |   9223372036854775807   |             2.000000             |
|     int16_t |   9223372036854775807   |             2.000000             |
|     int32_t |   4611686018427387903   |             4.000000             |
|     int64_t |   2305843009213693951   |             8.000000             |
|     uint8_t |   9223372036854775807   |             2.000000             |
|    uint16_t |   9223372036854775807   |             2.000000             |
|    uint32_t |   4611686018427387903   |             4.000000             |
|    uint64_t |   2305843009213693951   |             8.000000             |
|      size_t |   2305843009213693951   |             8.000000             |
|      double |   2305843009213693951   |             8.000000             |
| long double |   1152921504606846975   |             16.000000            |

N.B. max std::size_t is: 18446744073709551615

On ideone gcc 8.3I get:

ideone gcc 8.3 上我得到:

|  data types | approx max array length | max std::size_t / max array size |
|        bool |   9223372036854775744   |             2.000000             |
|        char |   18446744073709551615  |             1.000000             |
|      int8_t |   18446744073709551615  |             1.000000             |
|     int16_t |   9223372036854775807   |             2.000000             |
|     int32_t |   4611686018427387903   |             4.000000             |
|     int64_t |   2305843009213693951   |             8.000000             |
|     uint8_t |   18446744073709551615  |             1.000000             |
|    uint16_t |   9223372036854775807   |             2.000000             |
|    uint32_t |   4611686018427387903   |             4.000000             |
|    uint64_t |   2305843009213693951   |             8.000000             |
|      size_t |   2305843009213693951   |             8.000000             |
|      double |   2305843009213693951   |             8.000000             |
| long double |   1152921504606846975   |             16.000000            |

N.B. max std::size_t is: 18446744073709551615

It should be noted that this is a theoretical limit and that on most computers, you will run out of memory far before you reach this limit. For example, we see that for type charon gcc, the maximum number of elements is equal to the max of std::size_t. Trying this, we get the error:

应该注意的是,这是一个理论限制,在大多数计算机上,在达到此限制之前,您的内存就会耗尽。例如,我们看到对于类型charon gcc,元素的最大数量等于 的最大值std::size_t。尝试这个,我们得到错误:

prog.cpp: In function ‘int main()':
prog.cpp:5:61: error: size of array is too large
  char* a1 = new char[std::numeric_limits<std::size_t>::max()];

Lastly, as @MartinYork points out, for static arrays the maximum size is limited by the size of your stack.

最后,正如@MartinYork 指出的那样,对于静态数组,最大大小受堆栈大小的限制。