Ash*_*ley 3 c++ arrays automation dynamic
我已经开始学习 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;
}
Run Code Online (Sandbox Code Playgroud)
这是最近的 C++ 编译器中的新功能吗?它是否意识到我需要一个动态数组并创建它?
可能您正在使用 GCC 编译器,它有一个名为Arrays of Variable Length的扩展。
std::vector是 C++ 中真正的动态数组。
要在 GCC 中选择此标准,请使用选项 -std=c++11; 要获得标准要求的所有诊断信息,您还应该指定 -pedantic(或 -pedantic-errors,如果您希望它们是错误而不是警告)。