Is the size of an array constrained by the upper limit of int (2147483647)?

后端 未结 6 1310
梦谈多话
梦谈多话 2020-12-06 19:06

I\'m doing some Project Euler exercises and I\'ve run into a scenario where I have want arrays which are larger than 2,147,483,647 (the upper limit of

6条回答
  •  孤城傲影
    2020-12-06 19:56

    According to MSDN, the index for array of bytes cannot be greater than 2147483591. For .NET prior to 4.5 it also was a memory limit for an array. In .NET 4.5 this maximum is the same, but for other types it can be up to 2146435071.

    This is the code for illustration:

        static void Main(string[] args)
        {
            // -----------------------------------------------
            // Pre .NET 4.5 or gcAllowVeryLargeObjects unset
            const int twoGig = 2147483591; // magic number from .NET
    
            var type = typeof(int);          // type to use
            var size = Marshal.SizeOf(type); // type size
            var num = twoGig / size;         // max element count
    
            var arr20 = Array.CreateInstance(type, num);
            var arr21 = new byte[num];
    
            // -----------------------------------------------
            // .NET 4.5 with x64 and gcAllowVeryLargeObjects set
            var arr451 = new byte[2147483591];
            var arr452 = Array.CreateInstance(typeof(int), 2146435071);
            var arr453 = new byte[2146435071]; // another magic number
    
            return;
        }
    

提交回复
热议问题