Using memcpy with an array name

Possible duplicate:
C: How is the address of the array equal to its value?

I recently found code in my project that calls memcpy with the address of an array name

 int a[10]; memcpy(&a, &b ,sizeof(a)); 

Surprisingly (for me), it seems to work.

Should I change it to memcpy(a,b,sizeof(a)); ?

Is this permitted by the C ++ specification? Can someone point me to a resource about this behavior? Are there any pitfalls?

I also checked

 assert((void*)&a == (void*)a); 

and &a really matches a (besides this type).

I tested this behavior in VS2005, VS2008 and VS2010.

+4
source share
4 answers

&a is the address of the array; a can be implicitly converted to the address of the first element. Both have the same address, and therefore both values ​​will have the same value when converting to void* .

Are there any pitfalls?

memcpy not typical, so it's pretty easy to write code that compiles but behaves badly; for example, if a was a pointer, not an array, then sizeof a will compile, but give the wrong value. C ++ type templates can protect against this:

 std::copy(b, std::end(b), a); // will only compile if `b` has a known end. 
+4
source

The name of the array is evaluated at the address of the beginning of the array, so they have the same value. See Why is an array address equal to its value in C? (this is a C question, but the same is true for C ++).

+2
source

As you say, it does not matter.

When passed as a parameter, the name of the array "splits" into a pointer to its first element.

+1
source

Yes, the address of the array matches the address of its first element.
Therefore, there is no need to change the memcpy call. If you are not afraid that the definition of the array may change to a pointer later (for example, int* a = new int[10]; ).

Of course, if you are going to make changes to the program anyway, it is best to do without memcpy and use real C ++ instead.

+1
source

Source: https://habr.com/ru/post/1401135/


All Articles