Home >Backend Development >C++ >How are arrays and value types allocated on the stack and heap in C#?
Array Allocation and Value Types on Stack vs. Heap
In your code snippet:
int[] myIntegers; myIntegers = new int[100];
when you create the array myIntegers using the new keyword, the array itself is allocated on the heap, as suggested by the CLR. However, the integer elements within the array, being value types, are not boxed.
Stack and Local Variables
All local variables in a function, including value types and reference types, are allocated on the stack. The difference between the two lies in what is stored in these variables.
Example for RefTypes and ValTypes
Consider the following types:
class RefType { public int I; public string S; public long L; } struct ValType { public int I; public string S; public long L; }
The value of each type requires 16 bytes of memory: 4 bytes for I, 4 bytes for the S reference (or the actual S string for ValType), and 8 bytes for L.
If you have local variables of type RefType, ValType, and int[], they would be allocated on the stack as follows:
Stack: 0-3 bytes: RefType variable 4-7 bytes: ValType variable 8-11 bytes: int[] variable
Memory Layout
When assigning values to these variables:
refType = new RefType(); refType.I = 100; refType.S = "refType.S"; refType.L = 0x0123456789ABCDEF; valType = new ValType(); valType.I = 200; valType.S = "valType.S"; valType.L = 0x0011223344556677; intArray = new int[4]; intArray[0] = 300; intArray[1] = 301; intArray[2] = 302; intArray[3] = 303;
the values will be distributed in the following manner:
Stack: 0-3 bytes: Heap address of `refType` 4-7 bytes: Value of `valType.I` 8-11 bytes: Heap address of `valType.S` 12-15 bytes: Low 32-bits of `valType.L` 16-19 bytes: High 32-bits of `valType.L` 20-23 bytes: Heap address of `intArray`
Heap:
At refType's heap address:
At intArray's heap address:
**Passing Arrays**
The above is the detailed content of How are arrays and value types allocated on the stack and heap in C#?. For more information, please follow other related articles on the PHP Chinese website!