zrbecker
zrbecker

Reputation: 1582

Are C# arrays guaranteed to be stored sequentially in memory?

According to many sources on the internet, in C# arrays are stored sequentially. That is if I have a pointer to the first element in the array, say int *start = &array[0], then I can access array[i] by doing *(start + i).

However, I was looking through the C# Language Specification which is stored in C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC#\Specifications\1033 and I cannot find anyplace that guarantees that this will be the case.

In practice this might not be an issue, if say Microsoft and Mono keep their implementations in sync, but I was wondering if there is an official source that guarantees that arrays are stored sequentially in memory.

Thanks!

Upvotes: 4

Views: 1490

Answers (2)

David Waters
David Waters

Reputation: 12028

From the ECMA specification for the CLR:

I.8.9.1 Array types

....

Array elements shall be laid out within the array object in row-major order (i.e., the elements associated with the rightmost array dimension shall be laid out contiguously from lowest to highest index). The actual storage allocated for each array element can include platform-specific padding. (The size of this storage, in bytes, is returned by the sizeof instruction when it is applied to the type of that array’s elements.)

So yes in a compliment implementation of ECMA-335 Common Language Infrastructure elements in an a array will be laid out sequentially.

But there may be platform specific padding applied, so implementations on 64 bit platforms may chose to allocate 64bits for each Int32.

Upvotes: 5

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

Yes, one-dimensional, zero-based arrays (vectors) in .NET are stored sequentially. In fact, you can use unsafe code with pointers to access array elements one-by-one by incrementing the pointer.

ECMA-335 specification of CLI, section 1.8.9.1 says the following about arrays:

Array elements shall be laid out within the array object in row-major order (i.e., the elements associated with the rightmost array dimension shall be laid out contiguously from lowest to highest index). The actual storage allocated for each array element can include platform-specific padding.

Upvotes: 3

Related Questions