문제

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!

도움이 되었습니까?

해결책

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.

다른 팁

Why do they have the same effect on arr? What is the different between these calls?

Because the address of an array is the same as the address of its first element (arrays decay into pointers to their first element when passed to a function), it's just that they have a different type. arr has type char[10], that decays into char * when passed to a function. In contrast, &arr has the type char (*)[10] which doesn't change when passed as a function argument.

Which one would be considered the correct one?

As long as the function doesn't expect a specific type, i. e. it accepts void *, either one is good. If the called function, however, expects that either of the types be specified, then the other one should not be used, since then your program would be malformed and invoke undefined behavior.

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

They both contain the same value which is the address of the beginning of the array.

2- What is the different between these calls?

arr decays to a pointer to char, i.e. char* (this conversion happens when you pass the name of an array to a function) and &arr is a pointer to an array of char, i.e. char (*)[].

3- Which one would be considered the correct one?

I would use arr. memset accepts a void* which is the reason both work.

Also, note that char arr[10] = {}; can be used to zero initialize the array.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top