Copying an Array
Some languages allow you to copy the entire contents of an array into another array using a standard assignment statement, but often this is something that you need to take care of yourself.
You cannot use the assignment statement to copy arrays in C/C++. Instead, this can be achieved by manually copying the array yourself or by using the memcpy
function.
The memcpy
function copies a chunk of memory from one location to another.
The destination and source are void pointers (void *
) which is C’s way of saying “a pointer to anything”. You pass in the pointer to where to store the data (the left-hand side of an assignment normally), the source (the right-hand side), and the number of bytes to copy.
To determine the size of the data to copy, you use the sizeof
operator. You can read more on this in the C++ reference site.
The following code demonstrates the use of memcpy
and sizeof
to copy one array into another.