memset
sets 16 bytes (not bits) to 0. This is correct because the size of your array is 16 bytes, as you correctly stated (4 integers x 4 bytes per integer). sizeof
knows the number of elements in your array and it knows the size of each element. As you can see in the docs, the third argument of memset
takes the number of bytes, not the number of elements. http://www.cplusplus.com/reference/cstring/memset/
But be careful with using sizeof()
where you pass array as int x[]
or int* x
. For example the following piece of code will not do what you expect:
void foo(int arr[]) {
auto s = sizeof(arr); // be careful! this won't do what you expect! it will return the size of pointer to array, not the size of the array itself
...
}
int a[10];
foo(a);
solved How do this code work without any errors?