为什么VS要求数组大小不变,而MinGW不需要?它有办法吗?

Kai*_*ije 4 c++ mingw visual-studio

我已经使用代码:: blocks编写了一些来自Mingw的代码到visual studio及其编译器,它已经发现了很多错误,我的数组大小必须是常量!为什么VS需要一个恒定的大小而mingw不需要?

例如

const int len = (strlen(szPath)-20);
char szModiPath[len];
Run Code Online (Sandbox Code Playgroud)

len变量用红色下划线表示它是一个错误并说"预期的常量表达式"

我能想到解决这个问题的唯一方法是....

char* szModiPath = new char[len];
delete[] szModiPath;
Run Code Online (Sandbox Code Playgroud)

我是否必须将所有内容更改为动态或VS中还有其他方式吗?

Sig*_*erm 6

我能想到解决这个问题的唯一方法是....

这不是"唯一的方式".使用STL容器.

#include <string>

....
std::string s;
s.resize(len);
Run Code Online (Sandbox Code Playgroud)

要么

#include <vector>

....

std::vector<char> buffer(len);
Run Code Online (Sandbox Code Playgroud)

PS此外,我不认为在C++代码中使用匈牙利表示法是个好主意.


Pra*_*rav 5

为什么VS需要一个恒定的大小而mingw不需要?

因为可变长度数组不是C++的一部分,尽管MinGW(g ++)支持它们作为扩展.数组大小必须是C++中的常量表达式.

在C++中,始终建议使用std::vector而不是C-style arrays.:)