Reputation: 674
I am using visual studio 2013 express and MSVC compiler.
I get an error on executing the following lines of code.
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n];
return 0;
}
It says expression must have a constant value on the line on which I declare array a
.
I searched and found this c++ array - expression must have a constant value
It says you need to turn on a compiler option to allow it. How do I set that option in Visual studio express?
Upvotes: 1
Views: 2242
Reputation: 7374
You can use pointers
int*a = new int [n];
You have to delete before going out of your a
's scope:
delete[] a;
But better use vector:
vector<int> a(n);
You can also use llvm smallvector which is optimized for small arrays with no heap allocation if the size was small
llvm::SmallVector<int, 5> smallVector;
for(int i = 0; i < 5; i++) {
smallVector.push_back(i); } // No heap allocations have been performed up to this point.
smallVector.push_back(6); // heap allocation now
But keep in mind the compiler will decide where to allocate. Smallvector
Upvotes: 4
Reputation: 228
try the following:
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int *a=new int[n];
delete[] a;
return 0;
}
the way your doing it it gets allocated on the stack and for that it has to be constant whereas this way its on the heap and it can be whatever value.
i dont think there is a compiler option to change that
Upvotes: 1