C++:为什么 int array[size] 有效?

标签 c++ arrays dynamic automation

我已经开始学习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/

相关文章:

c++ - make中隐含规则的问题

javascript - 将动态生成的 div id 从 Rails 传递到 javascript/coffeescript

javascript - 如何使动态或生成的 HTML 页面可保存?

javascript - 如何创建一个从结束的 for 循环的索引末尾继续的循环?

javascript - 过滤与第二个数组中的值匹配的对象数组

mysql - 非平凡表达式的排序结果

c++ - 带有 phreads 的程序可以工作一段时间然后停止

c++ - 去除空格 (C++)

c++ - 在 gcc 和 MSVC/clang 之间使用 C++20 重载模板化相等比较运算符的不同结果

java - 将数组的索引作为值复制到新数组,按最高值排序。 java