
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Write your own memcpy() and memmove() in C++
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
#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
#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!
- Related Articles
- Write your own memcpy() in C
- Write your own atoi() in C++
- Write your own strcmp that ignores cases in C++
- How to write your own header file in C?\n
- memmove() function in C/C++
- memcpy() in C/C++
- memcpy() function in C/C++
- How to write your own LaTeX preamble in Matplotlib?
- Implement your own itoa() in C
- How will implement Your Own sizeof in C
- What is an Ansible Playbook and How to Write one on Your Own
- Print with your own font using C#
- Implement your own sizeof operator using C++
- How to write my own header file in C?
- Build Your Own Botnet

Advertisements