Allocates a block of memory on the stack.
type * ptr = stackalloc type [ expr ];
where:
A block of memory of sufficient size to contain expr elements of type type is allocated on the stack, not the heap; the address of the block is stored in pointer ptr. This memory is not subject to garbage collection and therefore does not have to be pinned (via fixed). The lifetime of the memory block is limited to the lifetime of the method in which it is defined.
stackalloc is only valid in local variable initializers.
Because
stackalloc is similar to
// cs_keyword_stackalloc.cs
// compile with: /unsafe
using System; class Test
{
public static unsafe void Main()
{
int* fib = stackalloc int[100];
int* p = fib;
*p++ = *p++ = 1;
for (int i=2; i<100; ++i, ++p)
*p = p[-1] + p[-2];
for (int i=0; i<10; ++i)
Console.WriteLine (fib[i]);
}
}
1 1 2 3 5 8 13 21 34 55