Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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!

like image 507
zrbecker Avatar asked Oct 16 '25 13:10

zrbecker


1 Answers

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.

like image 69
David Waters Avatar answered Oct 18 '25 08:10

David Waters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!