Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
karthikeya Boyini

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.