1

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!

Community
  • 1
  • 1
Jonathan
  • 752
  • 1
  • 9
  • 19

3 Answers3

4

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.

Community
  • 1
  • 1
Pubby
  • 51,882
  • 13
  • 139
  • 180
1

You are correct in believing the types are different. &myArray is a unsigned char(*)[] (a pointer to an array of unsigned char) and myArray (when passed to a function as an argument) becomes type unsigned char* (pointer to unsigned char). However, note that even though the types are different, there value is the same address. The reason both work with memcpy is because memcpy takes void* and doesn't care about the type.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166
1

what is the difference between myArray and &myArray?

They both point to the first element of myArray.

The name of an array usually evaluates to the address of the first element of the array, so myArray and &myArray have the same value.

memcpy function takes memory address to destination as input argument. As myArray and &myArray points to the same place, so the effort is the same:

void* memcpy( void* dest, const void* src, std::size_t count );

Parameters
dest   -     pointer to the memory location to copy to
src    -     pointer to the memory location to copy from
count  -     number of bytes to copy
billz
  • 44,644
  • 9
  • 83
  • 100