Computer >> Computer tutorials >  >> Programming >> C programming

Write your own memcpy() in C


Here we will see how to implement memcpy() function in C. The memcpy() function is used to copy a block of data from one location to another. The syntax of the memcpy() is like below −

void * memcpy(void * dest, const void * srd, size_t num);

To make our own memcpy, we have to typecast the given address to char*, then copy data from source to destination byte by byte. Just go through the following code to get better idea.

Example

#include<stdio.h>
#include<string.h>
void custom_memcpy(void *dest, void *src, size_t n) {
   int i;
   //cast src and dest to char*
   char *src_char = (char *)src;
   char *dest_char = (char *)dest;
   for (i=0; i<n; i++)
      dest_char[i] = src_char[i]; //copy contents byte by byte
}
main() {
   char src[] = "Hello World";
   char dest[100];
   custom_memcpy(dest, src, strlen(src)+1);
   printf("The copied string is %s\n", dest);
   int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
   int n = sizeof(arr)/sizeof(arr[0]);
   int dest_arr[n], i;
   custom_memcpy(dest_arr, arr, sizeof(arr));
   printf("The copied array is ");
   for (i=0; i<n; i++)
      printf("%d ", dest_arr[i]);
}

Output

The copied string is Hello World
The copied array is 10 20 30 40 50 60 70 80 90