How are arrays created and accessed

余生长醉 提交于 2019-11-27 08:33:27

问题


I understand(not completely why, though) that instances of primitive types such as int, float are stored on the stack and are not heap allocated. But I am a bit confused about how arrays of primitive types are stored and accessed. I have this question because System.Array is a reference type. And reference types are heap allocated.

int[] integers = {1,2,3,4,5};

How are these individual integers stored and accessed on the memory?


回答1:


Your "understanding" is flawed, basically. Value type values are sometimes stored on the stack - but not when part of an array or any other heap-based object. It's unfortunate that some people choose to make such a blanket statement around value types living on the stack, which then confuses others :(

Besides, the stack/heap distinction is an implementation detail...

See my article on memory for some more details, but definitely read Eric Lippert's blog post (linked in the previous paragraph) for more philosophical considerations. (Read his other posts on value types for even more information.)




回答2:


You have discovered the reason why the statement "value types are always stored on the stack" is obviously wrong. The truth is that the type of the object being stored is irrelevant to where it is stored. The correct rule is that values with short lifetimes are stored in storage from the short-term "stack" and values with long lifetimes are stored in storage from the long-term "heap".

When you put it that way, it is practically a tautology. Obviously short-lived stuff is allocated from the short-term store, and long-lived stuff is allocated from the long-lived store! How could it be otherwise? But when you put it that way, clearly the type is irrelevant except insofar as the type gives you a hint about the lifetime.

The contents of an array of ints is potentially long-lived, so the ints are allocated from the long-term store. The contents of a local variable of type int is typically short-lived, so it is typically allocated from the short-lived store.




回答3:


Array itself is always a reference type, so it's stored on heap. Elements of an array are stored on heap too, but always in a contiguous block of memory.




回答4:


This article by Jeffry richter written back in 2002 explains this concept very clearly.



来源:https://stackoverflow.com/questions/7793808/how-are-arrays-created-and-accessed

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