在C++中使用用户输入变量声明数组大小。不同的 IDE 会产生不同的结果?

Declaring Array Size with a User Input Variable in C++. Different results in different IDE's?

本文关键字:IDE 结果 C++ 用户 输入 数组 声明 变量      更新时间:2023-10-16

我需要创建一个程序,用户输入数组的所需大小,然后C 代码创建它,然后允许数据输入。

这在代码中有效,但在Visual Studio社区2015

中不行

当我将以下代码放在CodeBlocks版本13.12中时,它可以工作

#include<iostream>
using namespace std;
int main()
{
    int count;
    cout << "Making the Array" << endl;
    cout << "How many elements in the array " << endl;
    cin >> count;
    int flex_array[count];
    for (int i = 0; i < count; i = i + 1)
    {
        cout << "Enter the " << i << " term " << endl;
        cin >> flex_array[i];
    }
    for (int j = 0; j < count; j = j + 1)
    {
        cout << "The " << j << " th term has the value " << flex_array[j] << endl;
    }
    return 0;
}

但是,如果我在Visual Studio 2015中输入相同的代码(即版本14.0.25425),我会收到错误:

表达必须具有恒定值

知道为什么会发生这种情况?

c 没有可变的长度数组。一些编译器实施是 extension ,但它仍然不是C 语言的标准功能,也不是便携式的。

如果您想要一个运行时变量长度阵列,则使用std::vector

std::vector<int> flex_array(count);