memcpy() in C/C++


In this article we will be discussing the working, syntax and examples of memcpy() function in C++ STL.

What is memcpy()?

memcpy() function is an inbuilt function in C++ STL, which is defined in <cstring> header file. memcpy() function is used to copy blocks of memory. This function is used to copy the number of values from one memory location to another.

The result of the function is a binary copy of the data. This function doesn’t check for any terminating source or any terminating null character, it just copies the num bytes from the source.

Example

void memcpy( void* destination, void* source, size_t num);

Parameters

The function accepts following parameter(s) −

  • destination − This is the pointer to the location we want the output to be stored.
  • source − Character string which is used as the input.
  • num − It is the number of bytes that are to be copied.

Return value

This function returns the pointer to the destination where the data is being copied.

Example

Input

char str_1[10] = "Tutorials";
char str_2[10] = "Point";
memcpy (str_1, str_2, sizeof(str_2));

Output

string str_1 before using memcpy
Tutorials
string
str_1 after using memcpy
Point

Example

 Live Demo

#include <stdio.h>
#include <string.h>
int main (){
   char str_1[10] = "Tutorials";
   char str_2[10] = "Point";
   puts("string str_1 before using memcpy ");
   puts(str_1);
   memcpy (str_1, str_2, sizeof(str_2));
   puts("\nstring str_1 after using memcpy ");
   puts(str_1);
   return 0;
}

Output

string str_1 before using memcpy
Tutorials
string str_1 after using memcpy
Point

Example

 Live Demo

#include <stdio.h>
#include <string.h>
int main (){
   char str_1[10] = "Tutorials";
   char str_2[10] = "Point";
   puts("string str_1 before using memcpy ");
   puts(str_1);
   memcpy (str_1,str_2, sizeof(str_2));
   puts("\nstring str_2 after using memcpy ");
   puts(str_2);
   return 0;
}

Output

string str_1 before using memcpy
Tutorials
string str_2 after using memcpy
Point

Updated on: 17-Apr-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements