0

I need to set an array's size based on a user's input to cin in c++, and I can't figure out why it won't compile.

int input;
cin >> input;
const int N = input;
int array[N];

Shouldn't this work? I must be missing something.

2 Answers 2

6

Shouldn't this work?

It shouldn't.

I must be missing something.

You're missing the fact that the size of an array variable must be a compile time constant. A value provided by the user at runtime cannot possibly be known at compile time.

In order to create an array with a dynamic size, you need to create a dynamic array. Simplest way to do that is to use std::vector.

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

Comments

0

It is not possible to statically automatically allocate an array with variable size. The size of such an array must be compile-time constant: that is, its size is encoded in your executable, and so must be known to the compiler from reading your source code alone.

The two most common approaches for dynamic arrays are std::vectors, which are a neat little class that handles a lot of this for you, and creating arrays with the new keyword, which is junkier but has its place.

I'd recommend watching The Cherno's video on dynamic arrays here: https://www.youtube.com/watch?v=PocJ5jXv8No. It is a great primer on this topic.

4 Comments

In this case the attempt was to automatically allocate the array; not statically.
I'm not sure I'm following you. When you say "automatic", do you mean "dynamic"? It looks to me from the code sample that they were statically allocating when they wanted to do it dynamically.
No, by automatic I mean automatic; not dynamic. There are four storage durations for allocation: Automatic, dynamic, static, and thread. The example array has (or would have, if it was well-formed) automatic storage.
Thanks for the correction: I have been using the term "static" incorrectly for scope-based allocations on the stack.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.