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?

  • ***Is this method correct?*** No `std::vector` is the `c++` way to create a dynamic array. VLAs are not legal in the language. Related: [https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – drescherjm Jan 01 '21 at 18:11

2 Answers2

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

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • 1
    The OP can also use the `std::vector::push_back()` method and let the vector grow during runtime. – Thomas Matthews Jan 01 '21 at 18:48
  • @ThomasMatthews yup, I intentionally put that example because it's similar to what OP actually wants. Appreciate you reminded me of that though! – Rohan Bari Jan 01 '21 at 18:49
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.

Andy Newman
  • 1,178
  • 2
  • 8
  • 23