1

I need to create a program where the user enters the desired size of an array and the C++ code then creates it and subsequently allows data entry into it.

This works in the Code Blocks IDE but not in Visual Studio Community 2015

When I put the following code in CodeBlocks Version 13.12 it works

#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;
}

However, if I enter the same code in Visual Studio 2015 (i.e. Version 14.0.25425), I get the error:

expression must have a constant value

Any idea why this occurs?

ctd2015
  • 21
  • 2

1 Answers1

5

C++ doesn't have variable-length arrays. Some compilers implement is as an extension though, but it's still not a standard feature of the C++ language and it is not portable.

If you want a run-time variable length array use std::vector instead:

std::vector<int> flex_array(count);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks , need to add #include in the start of the code. STD doesn't seem to contain this. The compiler gives the message namespace std has no member vector – ctd2015 Dec 02 '16 at 10:15
  • @ctd2015: STD don't exist. std (lowercase) is a namespace. It's empty, until some declarations will fill it. Those declarations are inside the header, taht's part of the C++ standard: see http://en.cppreference.com/w/cpp/header – Emilio Garavaglia Dec 02 '16 at 10:33