0

I try to create an array. The size of it depends on the user's input. But how can I do it? or should I use string or vector instead?

I am new to C++. When I googled the problem, I still didn't get it. I tried the following code but it was not working.

const int t; cin >>t; double myarrary[t]={}; 

but my friends code works.

cin >> num; int px[num]={}; 

Thank you

1
  • Open your C++ book to the chapter that introduces you to the C++ library, and the std::vector template, and all will be explained. "Googling" is not a very good way to learn C++. The best way to do so is by learning from a good C++ book. Commented Mar 30, 2019 at 2:00

1 Answer 1

3

Variable length arrays like double myarrary[t] where t is a run-time value are a C feature. It is not in C++ standard, but some compilers do support that.

Use std::vector for portability.

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

5 Comments

but i set t as constant. Shouldn't it be treated as a constant?
@Www Working on some compilers doesn’t mean that you should write such code. Conformance to the standard does.
@Www How can it be a constant if you're reading user input into it after it was declared? By definition, the value of a const variable has to be initialized when it is declared and can't change after that. Also, array sizes need to be compile-time constants (the value is known during compile time), not just constant after the declaration.
@L.F. Conformance to the standard doesn't necessarily mean the code is good either.
@FeiXiang Oh yes! Definitely! It was only meant to be a comparison, but I worded it too ambiguously ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.