Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is an array of object[]s stored in memory?

As I understand it, the elements of an array are stored contiguously in memory, and accessing a particular one it is done by adding the product of the desired index and the size of each element with the base array address to find the address of the element.

Since in a language like C# I can create an array of object[]s and put whatever data type I want in it, how is each element of the array stored (and kept) at a uniform length if I used differently sized types while still allowing for random access?

like image 418
daniel Avatar asked Sep 08 '25 04:09

daniel


1 Answers

This depends on the language in question, and what you mean by "object" -

As you mentioned C#, in C# (.NET), an object[] contains an array of references to individual object instances. The array is an array of references - the object instance still needs to be assigned to an element of the array. The references are of a uniform size, but the object instances themselves are stored separately, and do not have to be the same size.

This is the same in most languages when storing an array of "references" or "pointers", and not the object instances themselves.

like image 140
Reed Copsey Avatar answered Sep 09 '25 23:09

Reed Copsey