Why is memset () not working properly when placed inside a loop body?

Yesterday I programmed a small piece of C ++ code that contains a loop and an array. In the program, I need to reset the array every time the loop starts. However, if I use

memset(sum,sizeof(sum),0); 

Then the array will not reset for all 0. For this program, I used:

 for (i=0;i<sizeof(sum)/sizeof(int);i++) sum[i]=0; 

instead.

However, I think the loop is not as clear as the function, and this requires an additional variable, not to mention that it is uncool a million times than the wizardry memset () function. Could you guys enlighten me on this?

+4
source share
5 answers

In fact, you write the size of the sum in the first bytes. You should do memset(sum,0,sizeof(sum)) instead.

(In other words, the arguments are target, data, and length, and you specified the data and length in the wrong order.)

+11
source

This is C ++, so do it with C ++ using fill_n .

std::fill_n(&sum[0], sizeof(sum) / sizeof(sum[0]), 0);

The reason your memcpy didn't work is because, as noted in other answers, you replaced the second and third arguments.

EDIT: fill and fill_n will work on what provides or can be thought of as an output iterator. For standard containers, such as vector , you can pre-set the container or use back_inserter , and for arrays you can use the specified form.

+7
source
 memset(sum,sizeof(sum),0); 

Wrong.

I think you wanted to write:

 memset(sum,0, sizeof(sum)); 

The signature of the memset function is as follows:

 void * memset ( void * ptr, int value, size_t num ); 

And his description :

Sets the first num bytes of the memory block pointed to by ptr to the specified value (interpreted as unsigned char).

+4
source

I think you have the parameters in the wrong order.

According to cplusplus.com , the size parameter should be the last:

 void * memset ( void * ptr, int value, size_t num ); 
+2
source

The syntax for the memset function is:

 void *memset(void *s, int c, size_t n); 

The memset () function fills in the first n bytes of the memory area pointed to by s with constant byte c.

So you need to:

 memset (sum, 0, sizeof(sum)); 
+1
source

All Articles