Why does std::fill erase my array?

Why does std::fill erase my array? The following code returns:
sizeof 4
sizeof 0

Why is the size of my array suddenly 0 after filling it with zeros? I was using this thread:

http://www.cplusplus.com/forum/beginner/17491/

1
2
3
4
5
6
7
  #include <iostream>
  using namespace std;
  int n = 4;
  int array[n];
  cout << "sizeof " << sizeof( array ) << "\n";
  std::fill( array, array + sizeof( array ), 0 );
  cout << "sizeof " << sizeof( array ) << "\n";
Last edited on
Your code is completely wrong, and if you read thread a liitle further , it will tell why.

in your case std::fill will try to assign 0 to array[0] through array[15] overwriting some memory it does not own and breaking your program. I am sure that if you will replace 0 with 1 in fill, you will probably get 1 as second sizeof.
Thanks MiiNiPaa. I had also reached the conclusion that my code is completely wrong. I'm currently trying to get it right.
What is wrong with canonical std::fill(std::begin(array), std::end(array), 0); which will also have a benefit of failing in compile time if array size cannot be known (like when array decayed to pointer)
Last edited on
I came up with this solution that uses vectors instead of arrays:

 
std::vector<int> array(n);


I'm not sure what the difference between them is, but I'll use vectors for now. Thanks.
Last edited on
Topic archived. No new replies allowed.