4

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.

Community
  • 1
  • 1
Mordy Shahar
  • 107
  • 8

4 Answers4

4

&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.
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

The name of an array evaluates to the address of the beginning of the array, so the two have identical meaning. See How come an array's address is equal to its value in C? (it's a C question but the same holds for C++).

Community
  • 1
  • 1
Graham Borland
  • 60,055
  • 21
  • 138
  • 179
1

Like you say, it doesn't matter.

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

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
1

Yes, the address of an array is the same as the address of its first element.
So there's no need to change the memcpy call. Unless you're afraid that the definition of the array might change to a pointer later (like int* a = new int[10];).

Of course, if you're going to make changes to the program anyway, it might be best to dispense with the whole memcpy and use real C++ instead.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150