Possible Duplicate:
C: How come an array's address is equal to its value?
I recently found code in my project that calls memcpy
with the address of array name
int a[10];
memcpy(&a, &b ,sizeof(a));
Surprisingly (to me) it seems to work.
Should I change it to memcpy(a,b,sizeof(a));
?
Is it allowed by the C++ spec? Can anyone point me to resource about this behavior? Are there any pitfalls?
I also checked
assert((void*)&a == (void*)a);
and &a
indeed is the same as a
(besides it's type).
I verified this behavior in VS2005, VS2008 and VS2010.
&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 so both will give the same value when converted to void*
.
Are there any pitfalls?
memcpy
is not typesafe, so it's quite easy to write code that compiles but behaves badly; for example, if a
were a pointer rather than an array, then sizeof a
would compile but give the wrong value. C++'s typesafe templates can protect against that:
std::copy(b, std::end(b), a); // will only compile if `b` has a known end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With