0
Help with initializing an array's size
#include<iostream> using namespace std; int main() { int n; cout<<" Enter the size of the array: "; cin>>n; int arr[n]; } // I get "error C2131: expression did not evaluate to a constant
7 Answers
+ 5
you can try using pointer like
int *arr= NULL;
arr= new int[n];
then when u dont want to use it anymore can delete it with
delete[] arr;
arr = NULL;
+ 3
it works fine for me maybe is a problem with ur compiler
+ 3
its a pointer
+ 1
When you initialize array 'arr' with 'n' you are making it a variable length array, meaning the compiler doesn't know the exact size of the 'arr' during compilation which makes it dynamic hence it can't allocate memory for it at runtime. The way you have initialized the array is not an acceptable way for a dynamic array initialization in c++, that is used for static array initialization.
When you want to allocate memory and don't know the value until run time, you need to use dynamic memory allocation. This is done in C++ with operator new. (But the memory you allocate yourself with new also needs to be freed with delete or delete[].)
change
int arr[n]:
to
int * arr = new arr[n];
PS Static array takes memory allocation from the Stack and Dynamic array takes memory allocation from the heap which is dynamic itself, which provides extra memory to a program at the time it is running.
0
my compuler is just VS2015 x64 Native Tools Command Prompt
it also says "failure was caused by non-constant arguments or reference to a non-constant symbol"
0
what does the * mean in *arr?
0
also that worked completely