-5

if we initialize a 2d array in c++ like:

    int n; 
    cin>>n;
    int a[n][1000]= {0};

why does it compile but not work properly? I tried to access a[4][2] which gave me 2 while it should give me 0 while in case of:

    int n;
    cin>>n; int a[n]= {0};

it works absolutely fine. Used a gcc c++14 compiler

  • 1
    That's not Standard C++. Also, please define "not work properly" – Rakete1111 Jun 05 '17 at 12:12
  • "not work properly" uh? – Federico klez Culloca Jun 05 '17 at 12:12
  • 1
    There's a (fairly intelligent) school of thought that says you probably shouldn't bother to use naked arrays in C++, similar to using `std::string` over `char` arrays. People who impose their C background on C++ are best referred to as C+ programmers :-) Accept the language in full and use real collections, such as `std::vector`. – paxdiablo Jun 05 '17 at 12:14
  • Don't use arrays when you want them to be dynamic(run time). C++ does not, per the standard, support variable length arrays. If you want a dynamic array use `std::vector`. – NathanOliver Jun 05 '17 at 12:14
  • 1
    As for the reason for failure: apart from UB it's probably a stack overflow. – Daniel Jour Jun 05 '17 at 12:20
  • What did it do that wasn’t working properly? As others have pointed out, VLAs aren’t supported by the C++ standard, but are supported by several compilers as a language extension; the details may depend on what compiler you’re using. If it isn’t a stack overflow, my guess is that you can’t create an array of VLAs and `int a[1000][n]` would have worked better. Then again, that’s something I’d expect the compiler to catch if it’s true in your specific compiler’s support for VLAs, so again, what compiler you use is relevant. – Daniel H Jun 05 '17 at 15:04

1 Answers1

0

why does it compile

The program is ill-formed. However, some compiler support variable length arrays as a language extension and so would allow both of the example programs that you show.

why ... but not work properly?

I suspect that you expected that the program would behave differently than it did behave. Why it would behave differently depends on what you expected. Or perhaps you tried to create a larger array than fits on the stack.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • I added some more details in the question.. It was that I was trying to do. Used a Gcc c++14 compiler – ANUBHAV UJJAWAL Jun 05 '17 at 20:15
  • @ANUBHAVUJJAWAL I could not reproduce your problem: http://coliru.stacked-crooked.com/a/25162f0a500166c6 I would recommend checking your compilers manual to see if value initialization of VLA is supported. I'm pretty sure that it is not allowed in C99, where VLA themselves are specified. – eerorika Jun 06 '17 at 00:39
  • What happened? Why could you not reproduce it? – ANUBHAV UJJAWAL Jun 06 '17 at 15:48
  • @ANUBHAVUJJAWAL see the link in the comment. What happened was that the output was 0, as one would expect. – eerorika Jun 06 '17 at 16:06