0

I was wondering if I do this:

int TOPE , vector[TOPE] ;
cin >> TOPE ;

Does vector get the amount of elements I input or does it have a number that I can't control?

MikeCAT
  • 69,090
  • 10
  • 44
  • 65
  • How is this question related with C#? – MikeCAT Jun 11 '21 at 13:50
  • 1
    **No**. Neither has C++ support for variable length arrays, and even your compiler has this feature, it will not resize the array after initializing. – user1810087 Jun 11 '21 at 13:52
  • 1
    You won't be able to make an arbitrary sized array, only something predefined (from a constant or a literal). Use `std::vector` for dynamic arrays – Alexey Larionov Jun 11 '21 at 13:53

2 Answers2

4

The variable vector is a Variable-Length Array (VLA). Standard C++ doesn't support that, but some compiler supports that as extension.

The variable TOPE is not initialized at the point where the variable vector is declared, so its size is indeterminate.

To set the size of VLA to the number entered, you should write like this:

int TOPE;
cin >> TOPE ;
int vector[TOPE] ;

To do it in more standard way, you should use std::vector instead of VLA:

int TOPE;
cin >> TOPE ;
std::vector<int> vector(TOPE);
MikeCAT
  • 69,090
  • 10
  • 44
  • 65
1

Firstly, VLAs, or variable-length array is not a C++ standard, although some compiler like gcc does support it. More info : Why aren't variable-length arrays part of the C++ standard?

Secondly, compilers read in a top-down fashion. Changing a variable after it has been used as length for an array isn't going to change the array in any way.

To declare it properly, declare it like this :

int TOPE; std::cin >> TOPE;
int vector[TOPE];
silverfox
  • 1,425
  • 6
  • 23