C++:为什么 int array[size] 有效? [英] C++: Why does int array[size] work?
问题描述
我已经开始学习 C++.我读到只能在运行之前设置数组的大小,并且可以在运行时设置动态数组.所以我期待这会失败,但它没有:
#include int main() {使用命名空间标准;整数大小;cout<<"输入数组大小:";cin >>尺寸;int i, score[size], max;//数组大小设置为变量不会失败cout<<结束<<"输入分数:\n";cin >>得分[0];最大值 = 分数 [0];for (i = 1; i < size; i++){cin >>得分[i];如果(分数 [i] > 最大值)最大值 = 分数 [i];}cout<<最高分是"<<最大<<结束;返回0;}
这是最近的 C++ 编译器的新特性吗?它是否意识到我需要一个动态数组并创建它?
可能你正在使用 GCC 编译器,它有一个扩展名为 可变长度数组.
std::vector 是 C++ 中真正的动态数组.><块引用>
要在 GCC 中选择此标准,请使用选项 -std=c++11;要获得标准要求的所有诊断信息,您还应该指定 -pedantic(或 -pedantic-errors,如果您希望它们是错误而不是警告).
I have started learning c++. I read that an array's size can only be set before run and dymanic arrays can be set during runtime. So I was expecting this to fail but it didn't:
#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;
}
Is this a new feature in recent C++ compilers? Is it realising I need a dynamic array and creating that instead?
Probably you are using GCC compiler, it has an extension called Arrays of Variable Length.
std::vector is the real dynamic arrays in 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] 有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!