C ‘memcpy’ Examples

The C memcpy command provides mechanism to copy a set of bytes from location to another. It is quite similar to the strcpy function. The advantage of memcpy is that you can copy strings, or bytes, or data, or structures, or anything you want. The memcpy function does not discriminate.

The C memcpy function definition:

The definition of the memcpy function takes 3 arguments and is defined in the string.h header file.

#include <string.h>
 
void *memcpy(void *dest, const void *src, size_t n);

The first argument is the copy destination, the place where you want your data to be copied to. The second argument is the source data, and finally the third argument is the size of the area you want to be copied, defined as the number of bytes. The programmer also must ensure that the memory areas are not overlapping memory areas. Once the copy is complete the function will return a pointer to the start of the newly copied data area.

C memcpy Examples

What is a memcpy examples article without an example?

#include <string.h>
#include <stdio.h>
 
int main(int argc, char **argv)
{
	int i, j;
 
	i = 10;
	memcpy(&j, &i, sizeof(i));
 
	fprintf(stdout, "J = %d\n", j);
 
	return 0;
}

This is just a silly example of using memcpy to copy the data at the address of i to the address of j. Thus the output from this function is:

$ ./main
J = 10

Obviously memcpy is far more powerful than this and we could copy data from one structure to another quite easily:

typedef struct {
  int i;
  char c;
} memcpy_ex_t;
 
int main(int argc, char **argv)
{
    memcpy_ex_t a, b;
 
    a.i = 123;
    a.c = 'e';
 
    fprintf(stdout, "Mem structure A: i = %u | c = %c\n", a.i, a.c);
 
    memcpy(&b, &a, sizeof(memcpy_ex_t));
 
    fprintf(stdout, "Mem structure B: i = %u | c = %c\n", b.i, b.c);
 
    return 0;
}

The output from this you can probably guess:

$ ./main 
Mem structure A: i = 123 | c = e
Mem structure B: i = 123 | c = e

You could even use memcpy to clear your structure or element by simply creating a structure that is zeroed. For example if we modify the above program, and looking at lines 3, 14, 16 specifically for the additions:

int main(int argc, char **argv)
{
    memcpy_ex_t a, b, c = { 0 };
 
    a.i = 123;
    a.c = 'e';
 
    fprintf(stdout, "Mem structure A: i = %u | c = %c\n", a.i, a.c);
 
    memcpy(&b, &a, sizeof(memcpy_ex_t));
 
    fprintf(stdout, "Mem structure B: i = %u | c = %c\n", b.i, b.c);
 
    memcpy(&b, &c, sizeof(memcpy_ex_t));
 
    fprintf(stdout, "Mem structure B: i = %u | c = %c\n", b.i, b.c);
 
    return 0;
}

The output then becomes:

$ ./main 
Mem structure A: i = 123 | c = e
Mem structure B: i = 123 | c = e
Mem structure B: i = 0 | c =

Your imagination … and the compiler are probably your limits. Be careful though, especially with overlapping memory locations and the cost of doing memory copies is not cheap.