简体   繁体   中英

Array memory Allocation clarification

Today i was reading a SO thread about array and its memory allocation. And i found an answer which was neatly explained and i must say its excellent.

But after reading that answer, i got few more questions which i kept asking myself about what i just read. So far still i am unable to answer it myself nor able to google it up. Hence i require your kind help in explaining those questions to me.

  1. Why is array getting created on heap when every of its content is getting stored on stack? Just 2 avoid boxing in case of value types?
  2. If above was true, then why array had 2 be created on heap first of all?

  3. When he said in his answer new int[100] is actually getting created on heap, is 400 (100 * 4) bytes getting allocated on heap? If so, why? because all the values are getting stored on stack

  4. If 1000 item array is created, then how on earth stack is enough to be stored? I know 1 MB is the size of the stack allocated. but in this case it will exceed. So whats the funda??

Please feel free to add your own questions or more info if you may have to this.

Thanks

When we say array is allocated on heap it means the values will be in heap. Array values are not stored on stack. I think this answers all 3 questions.

var myArray = new int[10];

Above line creates myArray variable on stack but the memory of array is allocated on heap and so all values stored in it also go in heap.

From what I understand, in a non-formal definition, value types are stored locally to where they are defined. So if a single value type is defined in a method, it will be stored on the stack. If it's defined as field on a class, or in this case, as items in an array, then the 'parent' object is on the heap so the value type will also be stored on the heap.

UPDATE

For more details on value types versus reference types and the stack, check out Eric Lippert's articles:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM