0

Declaring a regular array size with a variable? I thought not possible.

I've always assumed (from reading books) that when you declare an array e.g "int myarr[10];"...the 10 had to be a literal or a variable declared "const"...so why does this work. (please input 5 integers.) (see the array declaration enclosed in "############") (The code was in response to question on here...removing zeros from user-input) https://code.sololearn.com/cZBu2O857Jed/#cpp

23rd Jan 2020, 9:49 PM
rodwynnejones
rodwynnejones - avatar
2 ответов
+ 5
Initializing an array with a non-constant variable is called "variable length arrays" and is an extension on the C++ language by some compilers. It is not part of the C++ standard, so this may or may not work on every compiler. You might as well use an std::vector to get the 'same' results while using proper C++. In C, however, variable length arrays are part of the standard since C99.
23rd Jan 2020, 11:10 PM
Dennis
Dennis - avatar
+ 1
Thank you Dennis...I was a bit surprised it worked (I use code-blocks). Your suggestion on vectors is exactly what I suggested to the person I original replied to.......but then.... to double-check.....I had a go, and it worked. Thank you again for your response.
23rd Jan 2020, 11:44 PM
rodwynnejones
rodwynnejones - avatar