Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Objects are reference types. The value at the address is actually a pointer to the true element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top