Reputation: 47
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?
Upvotes: 0
Views: 896
Reputation: 33126
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)
.
Upvotes: 1
Reputation: 101476
memset
's 3rd paranneter is how many bytes to fill. So here you're telling memset
to set 10 bytes:
memset(arr,0,10);
But arr
isn't necesarrily 10 bytes. (In fact, it's not) You need to know how many bytes are in arr
, not how many elements.
The size of an int
is not guaranteed to be 1 byte. On most modern PC-type hardware, it's going to be 4 bytes.
You should not assume the size of any particular datatype, except char
which is guaranteed to be 1 byte exactly. For everything else, you must determine the size of it (at compile time) by using sizeof
.
Upvotes: 2
Reputation: 2288
Case #1: sizeof(arr)
returns 10 * sizeof(int)
Case #2: sizeof(int) * 10
returns the same thing
Case #3: 10
returns 10
An int takes up more than one byte (usually 4 on 32 bit). So if you did 40
for case three, it would probably work. But never actually do that.
Upvotes: 4