Write your own memcpy() and memmove() in C++

C++Server Side ProgrammingProgramming

memcpy() function is an inbuilt function that is used to copy data from source location to destination location.

Prototype of memcpy function −

void * memcpy(void *destination_location, void *source_location, size_t size)

We will character by character copy data from source to destination.

Program to show the implementation of the solution,

Example

 Live Demo

#include<stdio.h>
#include<string.h>
void MemcpyFunc(void *dest, void *src, size_t n){
   char *dataS = (char *)src;
   char *dataD = (char *)dest;
   for (int i=0; i<n; i++)
      dataD[i] = dataS[i];
}
int main() {
   char dataS[] = "Hello!";
   char dataD[100];
   MemcpyFunc(dataS, dataD, strlen(dataS)+1);
   printf("Copied string is %s", dataD);
   return 0;
}

Output

Copied string is Hello!

memmove() function is similar to memcpy(), it also copies data from source to destination char by char. It overcomes an issue of memcopy() which occures when the source and destination overlap each other.

In our memmove(), we will use a temporary array which handles overlapping source and destination problem.

Program to show the implementation of the solution,

Example

 Live Demo

#include<stdio.h>
#include<string.h>
void MemcpyFunc(void *dest, void *src, size_t n){
   char *dataS = (char *)src;
   char *dataD = (char *)dest;
   char *temp = new char[n];
   for (int i=0; i<n; i++)
      temp[i] = dataS[i];
   for (int i=0; i<n; i++)
      dataD[i] = temp[i];
}
int main() {
   char dataS[] = "Hello!";
   char dataD[100];
   MemcpyFunc(dataS, dataD, strlen(dataS)+1);
   printf("Moved string is %s", dataD);
   return 0;
}

Output

Moved string is Hello!
raja
Published on 17-Apr-2020 13:05:54
Advertisements