Search code examples
c++arraysmemset

memset on static array


I am a little confused about what to pass as the first parameter to memset when you have to set the elements of a static array. I've been searching but I couldn't find the answers to some specific questions I have.

If I have an array declared as:

char arr[10];

I have seen that these two calls are valid and produce the same effect:

memset( arr, 0, 10);
memset( &arr, 0, 10);

My specific questions are:

1- Why do they have the same effect on arr?

2- What is the different between these calls?

3- Which one would be considered the correct one?

Thank you!


Solution

  • Storage duration has nothing to do with it; an array is an array. This expression:

    &arr
    

    produces a char (*)[10], i.e., a pointer to an array of char with 10 elements. However, when arr is passed to a function like so:

    memset(arr, 0, 10);
    

    it degrades to a pointer to the first element, i.e., a char*. These are not the same thing. The "correct" (idiomatic) call is:

    memset(arr, 0, 10);
    

    However, in this case they are both converted to a void* when passed to memset and interpreted in the function as an unsigned char*. Since they both point to the same place it produces the same result.

    However, it is important to realize that, when dealing with the true respective types (i.e., not a void*), a pointer to an array is not the same as a pointer to the first element of an array.

    For example, incrementing a char (*)[10] will increment the pointer sizeof(char[10]) bytes, while incrementing a char* will increment only one byte.