0

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*;

?

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Dmitrii
  • 1
  • 1

3 Answers3

2

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.

M.M
  • 138,810
  • 21
  • 208
  • 365
0

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

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.

Zizheng Tai
  • 6,170
  • 28
  • 79
  • Yes,but why can't people improve the compiler for it to reserve memory after entering actual meaning of formal parameter i*?It will just need to multiply actual meaning of i* by 4 in our case,since the type of an array is int. – Dmitrii Aug 16 '15 at 01:10
  • @Dmitrii Because C++ doesn't work that way. Doing what you want would require additional infrastructure that the language was never designed to have. Sure, people could try to add such a thing. But the resulting language wouldn't be standard C++ anymore at that point. (And of course there's also the question of whether the benefit of this proposed feature is worth the effort required to implement it.) – TheUndeadFish Aug 16 '15 at 06:38
  • In this case the compiler will have to allocate memory for elements from 0 to EOF-1. – Dmitrii Aug 21 '15 at 17:12
  • Further more after cin>>i* operator the compiler will have to check first if there will be other cin>>i* operators and if they are it will still reserving memory for 0-EOF-1 elements till it reaches the last operator cin>>i* after what it will have to compare all i* entered and to allocate memory for (max i*)+1 and to free other reserved memory fo other purposes! – Dmitrii Aug 21 '15 at 17:20
  • This is for using only one array but maybe the coder will use several of them in this case if there is only one cin>>i* operator after which the compiler will allocate memory for (0-i*+1) elements. – Dmitrii Aug 21 '15 at 17:23