Why memset() does not work properly when placed inside a loop body?
Yesterday I programmed a small piece code in C++ which contains a loop and an array. In the program I need to reset the array every time the loop starts over. However, if I use
memset(sum,sizeof(sum),0);
Then the array won't be reset to all 0开发者_开发知识库. For this program I used:
for (i=0;i<sizeof(sum)/sizeof(int);i++) sum[i]=0;
instead.
However, I think a loop is not as clear as a function, and it requires an additional variable, not to mention this is a million times uncool than the wizardry of memset() function. Could you guys enlighten me on this?
You're actually writing the size of sum into the 0 first bytes.
You should be doing memset(sum,0,sizeof(sum))
instead.
(In other words, the arguments are target, data and length and you provided data and length in the wrong order.)
This is C++ so do it the C++ way with 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 swapped the second and third arguments.
EDIT: fill
and fill_n
will work on anything that provides or can be treated as an output iterator. For standard containers like vector
you can either pre-size the container or use back_inserter
while for arrays you can use the form I indicated.
memset(sum,sizeof(sum),0);
Wrong.
I think you wanted to write:
memset(sum,0, sizeof(sum));
The signature of memset
function is this:
void * memset ( void * ptr, int value, size_t num );
And its description is :
Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).
I think you have the parameters in the wrong order.
According to cplusplus.com, the size parameter should be last:
void * memset ( void * ptr, int value, size_t num );
The syntax of function memset is:
void *memset(void *s, int c, size_t n);
The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.
So you need:
memset (sum, 0, sizeof(sum));
精彩评论