Please don't judge me roughly,I am only a new one in coding with C++ however my question is next: why can't we declare an array with parametrical size,parameter of which we enter ourselves?For example:
int mas[i*];
cin>>i*;
?
Please don't judge me roughly,I am only a new one in coding with C++ however my question is next: why can't we declare an array with parametrical size,parameter of which we enter ourselves?For example:
int mas[i*];
cin>>i*;
?
You can do this:
int i;
if ( !(std::cin >> i) )
throw std::runtime_error("input failed");
std::vector<int> mas(i);
Please note that vector
is the way of writing a runtime-sized array in C++. C-style arrays are mostly present for historical compatibility and should be avoided.
In C++, an array is an object whose type is an array type, and the types of all variables and of all expressions are (statically) part of the program and must be known at compile time. In other words, the type of mas
must be known at compile time.
The only way you can create an object whose type is not known at compile time is with an array-new-expression, new T[n]
, but even in that case there is no value of that type: the only value you can recover from that expression is a value of type T *
containing the address of the first element subobject of the array object.
Because when you create an array the program need to allocate enough memory for its elements. In your example, the number of elements in the array is still unknown at the point the array is declared.