0
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?

1

2 Answers 2

2

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().

Sign up to request clarification or add additional context in comments.

2 Comments

The OP can also use the std::vector::push_back() method and let the vector grow during runtime.
@ThomasMatthews yup, I intentionally put that example because it's similar to what OP actually wants. Appreciate you reminded me of that though!
0

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.

2 Comments

Prefer to use operator new instead of malloc. The malloc function does not call constructors. Also, the new operator does not require casting.
Agreed completely. I reverted to old school C completely and probably shouldn't have.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.