Here we will see how to implement the memcpy() function in C language. The memcpy() function is used to copy a block of data from one location to another. The syntax of memcpy() is as follows -
void * memcpy(void * dest, const void * srd, size_t num);
To make our own memcpy, we have to typecast the given address to char* and then copy the data byte by byte from the source to the destination. Just read the following code to get a better idea.
#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</p><p>", 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]); }
The copied string is Hello World The copied array is 10 20 30 40 50 60 70 80 90
The above is the detailed content of Write your own memcpy() function in C language. For more information, please follow other related articles on the PHP Chinese website!