Search code examples
c++arrayspointersreferencememcpy

C++: When using memcpy, what is the difference between myArray and &myArray?


Possible Duplicate:
How come an array’s address is equal to its value in C?

In the situation:

int x = 5;
unsigned char myArray[sizeof (int)];

This line...

memcpy (&myArray , &x , sizeof (int));

... is producing identical results to:

memcpy (myArray , &x , sizeof (int));

I am very much a novice to C++, but I was under the impression that arrays are just a pointer to their data. I was shocked when &myArray was working identical to myArray. I would have thought it would be trying to copy to the ADDRESS of the pointer, which would be very bad!


Solution

  • Two things about arrays:

    • Arrays "decay" to pointers of their element type. This is why the second version is working. See this :Is an array name a pointer?

    • There is such a thing as a "pointer to array". They are rarely used, but look like this:


    int a[5];
    int (*b)[5] = &a; // pointer to an array of 5 ints
    

    The & operator when used on an array gives you a pointer to array type, which is why the following doesn't work:

    int* b = &a; // error
    

    Since memcpy's parameter is a void*, which accepts any pointer type, both &myArray and myArray work. I'll recommend going with myArray though as it's more idiomatic.