I'm learning now c ++, such a question: if I write

#include <iostream> using namespace std; int main(int argc, const char * argv[]) { int n; cin >> n; int a[n]; return 0; } 

what size will the array be: n or 2 ^ 32-1?

  • four
    - Where did you get 2^32 - 1, frankly, it is not clear. - According to the standard, C++ Variable Length Arrays prohibited (see 8.3.4.1 ) . - There are compilers that support them as extension'ы , see stackoverflow.com/questions/4151254/wheres-gs-vla-extension - Accordingly, depending on the compiler you are using, you will receive either a compilation error or an array of size n. - Costantino Rupert
  • @ Kitty: why not as an answer? - VladD
  • @VladD Well, I was late, while I was looking for a reference in the standard, and there they already answered correctly :) - Costantino Rupert

2 answers 2

And why should he be 2 ^ 32 -1? It will be exactly how much you enter. Another thing is that this is not the standard C ++ extension. In gcc this will work, I don't know about other compilers.

  • @KoVadim: and the size is not in the sense of sizeof, but in the sense of the number of elements, as your example shows. (Since sizeof is a compile time constant.) - VladD

if i write

why don't you try and write this and see that this nonsense of yours doesn't even compile, since the size of the array should be known at the compilation stage?

ZY since I’ve been authoritatively corrected ( @KoVadim , thanks), I’ll add that if some compilers eat it (word, surprise), then to check the size of the array, you can make sizeof (a)

ZZY What a shame

  • one
    depending on the compiler, it may compile . g ++ (4.7) ( proof ) compiles this calmly. clang also. And the Intel compiler does not even swear. sizeof will show the size in bytes, it will be necessary to further divide by the size of the element. - KoVadim
  • @DreamChild: this is a nonstandard extension for gcc, works the same as alloca . - VladD