-1

Visual Studio is giving error while compiling this c++ code. It says that size should be a constant variable. I have tried making it constant but it does not work.

int size; cout << "Please Enter the array size : " ; cin >> size; int myArr[size]; 
4
  • 1
    You don't want to write code like this - it's a misfeature of C that g++ makes the default, but VisualC++ (correctly) does not. Commented Sep 29, 2018 at 22:42
  • You might look at alloca / _alloca, which have the same effect. Commented Sep 29, 2018 at 22:53
  • @Paul alloca is not part of C++. Commented Sep 29, 2018 at 23:07
  • @NeilButterworth I am aware, but the 'big 3' do support it. Commented Sep 30, 2018 at 10:45

1 Answer 1

0

The size of an array must be known at compile time. In your case, the size is known at runtime so you must allocate the array from the heap.

int size; std::cin >> size; int* myArr = new int[size]; // ... delete[] myArr; 
Sign up to request clarification or add additional context in comments.

13 Comments

But don't do this - use a std::vector.
It's not because of the memory management, it's because it makes life so much easier - for example, passing things to functions. And you can create a fixed-sized vector at construction-time. The need to do that is somewhat rare, but you can do it. I doubt very much the OP has this issue.
If you really don't want std::vector (e.g. because there is no simple way to resize it without initializing the new elements, or because it's slightly larger than a plain pointer), then use std::unique_ptr<T[]>.
@BradyDean As I said, in that case you can use auto array = std::make_unique<int[]>(n);. Under the hood it's no different from manually using new/delete, except you can't forget to delete the memory. Also you get exception safety: memory is freed even if something throws. On the other hand, with manual new/delete calls there is no sane way to work with exceptions without getting leaks.
@Holy What is the advantage of that over using a vector?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.