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

浪尽此生 提交于 2021-01-28 06:08:49

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/12118511/how-is-an-array-of-objects-stored-in-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!