int a;
cin>>a;
int arr[a];
I want to declare an array according to size of the user. I am new to programming . What can be done? Is this method correct?
int a;
cin>>a;
int arr[a];
I want to declare an array according to size of the user. I am new to programming . What can be done? Is this method correct?
The thing you want to achieve is called Variable Length Array, in short VLA which isn't a part of C++ standard.
What can be done?
It invokes an undefined behavior.
Is this method correct?
Nope. The best opportunity of taking a little help of std::vector<>
worth here. It dynamically allocates the requested bytes of data and optionally, you can initialize them with their required values.
You can achieve this like:
int n = 0;
std::cin >> n; // make sure it's a valid size
std::vector<int> a(n);
In case you wants it to keep growing runtime, just use its push_back()
method and you can get the vector size through its size()
.
You've tagged this C++, in which case there are very few excuses not to solve this with a std::vector.
If you must do it C style you can write:
int a;
cin >> a;
int * arr = (int *)malloc(sizeof(int) * a);
or better (as per Thomas' comment below):
int a;
cin >> a;
int * arr = new int[a];
but a vector is definitely preferred.