Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't stackalloc be used in C# to initialize a previously declared pointer?

Tags:

c#

stackalloc

I just discovered the stackalloc notation of C# has an unbelievable quirk, please see the following code:

//          int *p;
//          p = stackalloc int[42];  // won't work! 
//  Error CS1525: Unexpected symbol `stackalloc' (CS1525) 

            int *p = stackalloc int[42]; //works

My intention is to use stackalloc in a ternary expression like this:

int *p = size > 0xFFFFF ? (int*)Marshal.AllocHGlobal(size).ToPointer() : stackalloc int[size];

The totally unexpected strike of compiler shocked me hard. I'd really appreciate if someone could shed some light on this strange behavior. I've tested it on both mono and .net, neither works.

like image 644
Need4Steed Avatar asked Dec 09 '22 19:12

Need4Steed


1 Answers

http://msdn.microsoft.com/en-us/library/cx9s2sy4(v=vs.100).aspx
You can use stackalloc only when declaring and initializing a local variable.

like image 187
Alex Avatar answered May 16 '23 07:05

Alex