是否有必要仅在您定义指向它的指针的同一行中使用 `stackalloc`?
Is it necessary to use `stackalloc` only in the same line you define the pointer to it?
在下面的代码中:
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;
}
}
有什么方法可以去掉多余的变量temp
?
代码:
a[i] = stackalloc double[n];
有编译器错误:
Severity Code Description Project File Line Suppression State
Error CS8346 Conversion of a stackalloc expression of type 'double' to
type 'double*' is not possible.
Is it necessary to use stackalloc
only in the same line you define the pointer to it?
是的,这是必要的according to the C# language specification。
具体来说,请参阅 堆栈分配 部分,其中将语法指定为:
local_variable_initializer_unsafe
: stackalloc_initializer
;
stackalloc_initializer
: 'stackalloc' unmanaged_type '[' expression ']'
;
如您所见,您必须将local_variable_initializer_unsafe
与stackalloc_initializer
一起使用,这意味着您必须声明一个局部变量以使用结果进行初始化stackalloc
.
(从技术上讲,您可以根据需要在语句中放置任意多的换行符,但我很确定这不是您要问的!)
在下面的代码中:
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;
}
}
有什么方法可以去掉多余的变量temp
?
代码:
a[i] = stackalloc double[n];
有编译器错误:
Severity Code Description Project File Line Suppression State Error CS8346 Conversion of a stackalloc expression of type 'double' to type 'double*' is not possible.
Is it necessary to use
stackalloc
only in the same line you define the pointer to it?
是的,这是必要的according to the C# language specification。
具体来说,请参阅 堆栈分配 部分,其中将语法指定为:
local_variable_initializer_unsafe
: stackalloc_initializer
;
stackalloc_initializer
: 'stackalloc' unmanaged_type '[' expression ']'
;
如您所见,您必须将local_variable_initializer_unsafe
与stackalloc_initializer
一起使用,这意味着您必须声明一个局部变量以使用结果进行初始化stackalloc
.
(从技术上讲,您可以根据需要在语句中放置任意多的换行符,但我很确定这不是您要问的!)