Here is this code:

#include <iostream> void toZero(int *mass, int length) { int res[7]; for (int i = 0; i < length; ++i) { res[i] = 0; } mass = res; } int main() { int mass[] = {1, 2, 3, 4, 5, 6, 7}; toZero(mass, 7); for (int i = 0; i < 7; ++i) { std::cout << *(mass + i) << " "; } return 0; } 

Result of performance:

 1 2 3 4 5 6 7 

Question: In the toZero function toZero first element of the mass array after the line mass = res; must (?) refer to the first element of the res array. But this does not happen, why?

  • How do you understand what is not happening? In the debugger, see? - Vladimir Gamalyan
  • one
    Because when you call toZero , a local variable mass is created, into which the mass value from the main function (that is, the address of the first element of the array) is placed. After exiting the toZero function toZero this local variable is destroyed, and the mass from main is obviously not changed. - user194374
  • mass is a local variable, you change it mass = res , but don't use it anywhere else - Vladimir Gamalyan
  • Thank! I understood, but how to do it right? - faoxis
  • 1) Make a res declaration from a function, since it is also a local variable. 2) To transfer to toZero not int* , but int** . - user194374

1 answer 1

Try this:

 void toZero(int *mass, int length) { for (int i = 0; i < length; ++i) { mass[i] = 0; } } 

And instead of writing toZero, you can use the standard algorithm:

 #include <iostream> #include <algorithm> int main() { const int size = 7; int mass[size ] = {1, 2, 3, 4, 5, 6, 7}; std::fill_n(mass, size, 0); for (int i = 0; i < 7; ++i) { std::cout << *(mass + i) << " "; } return 0; } 

At the request of the audience:

 #include <iostream> #include <algorithm> #include <iterator> int main() { const int size = 7; int mass[size] = {1, 2, 3, 4, 5, 6, 7}; std::fill_n(mass, size, 0); std::copy(mass, mass + size, std::ostream_iterator<int>(std::cout, ",")); return 0; } 
  • And fill_n and memset is the same? - pavel
  • one
    @pavel, no. If you have an array of objects that are not POD types, then memset will create a subtle bug that will not appear on every compiler. - yrHeTaTeJlb
  • @pavel, although probably in some (or maybe in many) implementations of the standard library std::fill_n for POD types, it was done using memset, and for others with a loop and copy assignment operator - yrHeTaTeJlb
  • By the word std::fill_n will not nullify arrays of POD objects if the objects do not support the corresponding operator ( = ). memset in this regard goes ahead) (with the corresponding problems, of course) - Vladimir Gamalyan
  • @VladimirGamalian, but can you give an example of a POD type for which the compiler does not generate operator =? - yrHeTaTeJlb