声明C++具有动态大小的数组类型在 Linux 中工作正常,但不能在 Windows 中工作

Declare C++ array type with dynamic size works fine in Linux, but not Windows

本文关键字:工作 Linux Windows 但不能 类型 C++ 动态 数组 声明      更新时间:2023-10-16

使用最近的 gcc 版本,我可以声明动态大小的数组数据类型,如下所示:

#include <stdio.h>
int main() {
int u;
scanf("%d", &u);
using my_type = int[u];
printf("size of my_type: %dn", sizeof(my_type));
return 0;
}

这成功地与gcc编译,并且在Linux中工作正常。例如,输入 5 作为输入,这将打印 20。

但是对于Windows编译器cl.exe或VS2015本身,我收到编译错误:

error C2540: non-constant expression as array bound

我该如何解决这个问题?

这不是有效的便携式C++。这是GCC的C99扩展(可变长度数组(,在任何Visual Studio版本中都不可用。