在D语言中,数组的大小必须是在编译时确定的常量。在上述代码中,变量d是在运行时才能确定其值,因此无法在数组定义中使用。

解决方案1:将数组大小改为常量

import std.stdio;

void main()
{
    const d = "hello".length;
    int[d] arr = [1,2,3,4,5];
    writeln(arr);
}

在这个解决方案中,我们将变量d改为了常量,因此可以在数组定义中使用。

解决方案2:使用动态数组

import std.stdio;

void main()
{
    int[] arr = [1,2,3,4,5];
    writeln(arr);
}

在这个解决方案中,我们使用了动态数组,不需要在定义时指定数组的大小。


原文地址: https://www.cveoy.top/t/topic/fFrN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录