Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using memcpy with array name [duplicate]

Tags:

c++

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.

like image 240
Mordy Shahar Avatar asked Feb 22 '23 04:02

Mordy Shahar


1 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 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.
like image 132
Mike Seymour Avatar answered Mar 01 '23 01:03

Mike Seymour