-3

I wrote this code but got out of memory exception in the line if I am passing the range value 46542.

long[,] array = new long[range, range];

How to resolve this?

int noOfTestCases = Convert.ToInt32(Console.ReadLine());
if(noOfTestCases>=1 && noOfTestCases<=100)
{
    for(int i=0; i<noOfTestCases; i++)
    {
        Console.WriteLine("Enter the Range");
        long range = Convert.ToInt64(Console.ReadLine());
        long[,] array = new long[range, range];
    }
}
Christos
  • 53,228
  • 8
  • 76
  • 108
amit325
  • 101
  • 1
  • 7

2 Answers2

3

How to resolve this?

Choose a range that is smaller than 46,341. The largest number of elements in an array is Int32.MaxValue, or 2,147,483,647.

Since you're creating an NxN array, the largest size of one side of the "square" is Math.Sqrt(Int32.MaxValue) or 46340.950001052.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
2

The maximum size you can have as an indexer in an array is System.Int32.MaxValue, which is smaller than some Int64 numbers. Hence you get this exception.

Christos
  • 53,228
  • 8
  • 76
  • 108