9

today I started wondering about something in the MSDN. This article demonstrates, how one can increase the memory allocatable by an array under .NET 4.5 and x64. This is a nice feature, but something in the description provided by Microsoft baffeles me.

Under the section "Remarks" they say, that:

The maximum index in any single dimension is 2,147,483,591 (0x7FFFFFC7) for byte arrays and arrays of single-byte structures, and 2,146,435,071 (0X7FEFFFFF) for other types.

Since I mainly have int[] or double[] the latter number is relevant for my indexing. I can create an array with int[] TestArray = new int[2146435071], which is fine. However, under the same section Microsoft states:

The maximum number of elements in an array is UInt32.MaxValue.

Which is (according to the MSDN):

The value of this constant is 4,294,967,295; that is, hexadecimal 0xFFFFFFFF.

Now. If I get that right, I can have an array with up to 4,294,967,295 elements (for example ints) but due to the array being indexed by an int and not an uint I am not able to access the "upper" half of my data?

This confuses me a lot, sice it seems I am missing something essential here.

I hope you can enlighten me

Kind Regards

EDIT:

I understand that I can create multi-dimensional arrays, but an array of length 2e9 an width 2 seems a bit stupid. Aren't multi-dimensional arrays mapped to one-dimensional ones anyway?

1
  • I assume that the "maximum number of elements" is higher because it allows for multi-dimensional arrays. new byte[4000000000] would not be allowed, but new byte[4000,1000000] would.
    – Douglas
    Jan 28, 2014 at 14:59

1 Answer 1

4

The maximum index in any single dimension is 2,147,483,591

Remember that arrays can have multiple dimensions, so you could have a 2-D array that has up to 4,294,967,295 items, but each dimension can have a max length of 2,147,483,591.

So you can have a 2,147,483,591 X 2 array, but not a 1,000,000 X 1,000,000 array.

7
  • But I always thought, multi-dimensional arrays are mapped to one-dimensional ones? Jan 28, 2014 at 15:04
  • @lhiapgpeonk No - they are not.
    – D Stanley
    Jan 28, 2014 at 15:11
  • 2
    @lhiapgpeonk They're stored in one sequential block of memory. That's not quite the same thing.
    – Servy
    Jan 28, 2014 at 15:11
  • At least in C they were, weren't they? Jan 28, 2014 at 15:12
  • 1
    @lhiapgpeonk That's because C doesn't have real indexers, but just translates that pointer math (which is why you have a horde of buffer overrun security holes), but that can't be done in C# without unsafe code. Lots of things can be done in C that shouldn't be done...
    – D Stanley
    Jan 28, 2014 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.