Search code examples
c#pointersunsafestackalloc

Is it necessary to use `stackalloc` only in the same line you define the pointer to it?


In the following code:

unsafe
{
    int m = 10;
    int n = 10;
    double*[] a = new double*[m];
    for (int i = 0; i < m; i++)
    {
        double* temp = stackalloc double[n];
        a[i] = temp;
    }
}

Is there any way to remove the superfluous variable temp?

The code:

a[i] = stackalloc double[n];

has compiler error:

Severity Code Description Project File Line Suppression State Error CS8346 Conversion of a stackalloc expression of type 'double' to type 'double*' is not possible.


Solution

  • Is it necessary to use stackalloc only in the same line you define the pointer to it?

    Yes, this is necessary according to the C# language specification.

    Specifically, see the section on Stack Allocation which specifies the grammar as:

    local_variable_initializer_unsafe
        : stackalloc_initializer
        ;
    
    stackalloc_initializer
        : 'stackalloc' unmanaged_type '[' expression ']'
        ;
    

    As you can see, you must use local_variable_initializer_unsafe with the stackalloc_initializer, which means that you must declare a local variable to initialise with the result of the stackalloc.

    (Technically you can put as many line breaks into the statement as you like, but I'm pretty sure that's not what you were asking!)