1

I have initialized an array like this array[n][k+1]={0} where n and k are user input. But I found that it doesn't initialize all index values to zero. While on the other hand memset(array,0,sizeof(array)) works fine. So why this happened?

Because each time I initialised like this array[n][n]={0}, it always works fine. But why not in this case.

  • 4
    "`array[n][k+1]={0}` where n and k are user input." is not valid c++. – cigien Sep 25 '20 at 18:06
  • 3
    Unless `n` and `k` are compile time constants, `array[n][k+1]` is not legal C++ and any result you get is what you get. – NathanOliver Sep 25 '20 at 18:06
  • 3
    *"n and k are user input"*. VLA is not valid C++. it is an extension. – Jarod42 Sep 25 '20 at 18:06
  • Related to the VLA: [https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – drescherjm Sep 25 '20 at 18:08
  • 1
    Why you don't get the expected initialization comes down to compiler implementers and how they decide to deal with a non-standard extension. I suspect it's because this is the behaviour required by C99. – user4581301 Sep 25 '20 at 18:10
  • 1
    Looked it up. I'm wrong. C99 flat-out rejects initialization, so this is the C++ compiler implementers just doing whatever they felt like. I really need to update my copy of K&R. – user4581301 Sep 25 '20 at 18:16
  • 3
    And yet another person is taken in by the fool's gold of variable-length-arrays. @OP -- Use `std::vector> myarray(n, std::vector(k+1));` -- Not only is that going to work because it is standard, it sets the array to all `0`. – PaulMcKenzie Sep 25 '20 at 18:25

0 Answers0