Kordy Kordy - 2 months ago 5
C++ Question

How do this code work without any errors?

I've this code i wrote that sets the array to 0

int arr[4];
memset(arr, 0, sizeof (arr));


Very simple, but how the code works without any errors even though
sizeof(arr)
= 16 (4 the array size * 4 for int) and the size i used when i declared the array is 4, How
memset
sets 16 bits to zero and the array i passed as a parameter has the size of 4?

I used
memset(arr, 0, sizeof(arr)/sizeof(*arr));
to get the real size of the array and the result was accurate and it gives me
4
but how the above code works correctly?

Answer

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);
Comments