memcpy – copy the memory contents from one place to another

The memcpy function, does not really care about the parameters passed in, if they are the same types or of different types. Just that they are variables already declared (and of course can hold the data being passed from one place to another, because otherwise there may be a slight overlap if the copied value is larger in memory size to the copier).

So the memcpy is just a binary data copy and nothing else, there is no type checking.

Here is a example in c++ code that will copy a newly created struct(ure) from one place to another.

void* memcpy (void *copied_to, const void *copier, size_t num);

where the return is also the copied_to value, since we are not altering the copier then a const(ant) can be applied and the last parameter is num which is the size of the data you want to copy.

#include <stdio.h>
#include <string.h>
 
// diferent type of object, e.g. not a int,char
typedef struct 
{
    int bob;
} insertType;
 
int main()
{
  // create two variables of insertType with default values for bob of 10 and 20
  insertType t1 = { 10 };
  insertType t2 = { 20 };
 
  // output the declared values
  printf("t1 = %d\nt2 = %d\n", t1.bob, t2.bob);
 
  // do a memory copy of t2 into t1 only copy as big as the variable size.
  memcpy(&t1, &t2, sizeof(insertType));
 
  // output the new values
  printf("t1 = %d\nt2 = %d\n", t1.bob, t2.bob);
  return 0;
}

here is the output

t1 = 10
t2 = 20
t1 = 20
t2 = 20

also note that the size_t is a unsigned integral type (normal of int, of the base operating system)

Leave a Reply

Your email address will not be published. Required fields are marked *