Help with initializing an array's size | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

14th Jan 2017, 6:42 AM
Adrian Darian
Adrian Darian - avatar
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;
14th Jan 2017, 7:03 AM
Kawaii
Kawaii - avatar
+ 3
it works fine for me maybe is a problem with ur compiler
14th Jan 2017, 6:45 AM
Kawaii
Kawaii - avatar
+ 3
its a pointer
14th Jan 2017, 7:05 AM
Kawaii
Kawaii - avatar
+ 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.
14th Jan 2017, 7:15 AM
Akash Middinti
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"
14th Jan 2017, 6:50 AM
Adrian Darian
Adrian Darian - avatar
0
what does the * mean in *arr?
14th Jan 2017, 7:03 AM
Adrian Darian
Adrian Darian - avatar
0
also that worked completely
14th Jan 2017, 7:04 AM
Adrian Darian
Adrian Darian - avatar