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

后端 未结 12 1657
深忆病人
深忆病人 2020-11-22 07:21

Is there a max length for an array in 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?

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 07:55

    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.

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

提交回复
热议问题