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

Www
  • 53
  • 8
  • 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](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Sam Varshavchik Mar 30 '19 at 02:00

1 Answers1

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.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • but i set t as constant. Shouldn't it be treated as a constant? – Www Mar 30 '19 at 02:14
  • @Www Working on some compilers doesn’t mean that you should write such code. Conformance to the standard does. – L. F. Mar 30 '19 at 03:11
  • @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. – eesiraed Mar 30 '19 at 04:40
  • @L.F. Conformance to the standard doesn't necessarily mean the code is good either. – eesiraed Mar 30 '19 at 04:42
  • @FeiXiang Oh yes! Definitely! It was only meant to be a comparison, but I worded it too ambiguously ... – L. F. Mar 30 '19 at 05:03