Printer Friendly Version      Send     
Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio .NET
Reference
Visual C# Language
C# Keywords
Operator Keywords
 stackalloc
This page is specific to
Microsoft Visual Studio 2003/.NET Framework 1.1

Other versions are also available for the following:
C# Programmer's Reference
stackalloc

Allocates a block of memory on the stack.

type * ptr = stackalloc type [ expr ];

where:

type
An unmanaged type.
ptr
A pointer name.
expr
An integral expression.

Remarks

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 A.2 Pointer types are involved, stackalloc requires unsafe context.

stackalloc is similar to _alloca in the C run-time library.

Example

// 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]);
   }
}

Output

1
1
2
3
5
8
13
21
34
55

See Also

C# Keywords | Operator Keywords

© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker