我已经开始学习c++了。我读到数组的大小只能在运行前设置,动态数组可以在运行时设置。所以我期待这会失败,但它没有:
#include <iostream>
int main() {
using namespace std;
int size;
cout << "enter array size:";
cin >> size;
int i, score[size], max; //array size set to variable doesn't fail
cout << endl << "enter scores:\n";
cin >> score[0];
max = score[0];
for (i = 1; i < size; i++)
{
cin >> score[i];
if (score[i] > max)
max = score[i];
}
cout << "the highest score is " << max << endl;
return 0;
}
这是最近 C++ 编译器的新特性吗?它是否意识到我需要一个动态数组并改为创建它?
最佳答案
可能您正在使用 GCC 编译器,它有一个名为 Arrays of Variable Length 的扩展名.
std::vector是C++中真正的动态数组。
To select this standard in GCC, use the option -std=c++11; to obtain all the diagnostics required by the standard, you should also specify -pedantic (or -pedantic-errors if you want them to be errors rather than warnings).
关于C++:为什么 int array[size] 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17947378/