What is the difference between the following three commands?
Suppose we declare an array arr having 10 elements.
int arr[10];
Now the commands are:
Command 1:
memset(arr,0,sizeof(arr));
and Command 2:
memset(arr,0,10*sizeof(int));
These two commands are running smoothly in an program but the following command is not
Command 3:
memset(arr,0,10);
So what is the difference between the 3 commands?
memset(arr,0,sizeof(arr))
fills arr
with sizeof(arr)
zeros -- as bytes. sizeof(arr)
is correct in this case, but beware using this approach on pointers rather than arrays.
memset(arr,0,10*sizeof(int))
fills arr
with 10*sizeof(int)
zeros, again as bytes. This is once again the correct size in this case. This is more fragile than the first. What if arr
does not contain 10 elements, and what if the type of each element is not int
. For example, you find you are getting overflow and change int arr[10]
to long long arr[10]
.
memset(arr,0,10)
fills the first 10 bytes of arr
with zeros. This clearly is not what you want.
None of these is very C++-like. It would be much better to use std::fill
, which you get from the <algorithm>
header file. For example, std::fill (a, a+10, 0)
.