Home > Backend Development > C++ > body text

Write your own memcpy() function in C language

WBOY
Release: 2023-08-25 15:17:04
forward
1725 people have browsed it

Write your own memcpy() function in C language

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);
Copy after login

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.

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</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]);
}
Copy after login

Output

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!