Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

C++ cstring memmove() Function



The C++ cstring memmove() Function is used to move the data from one memory buffer to another memory. This function is defined in cstring header file.

It is similar to memcpy() function, but instead of copying data, it moves data from one memory buffer to another memory buffer. This functionality help us to avoid undefined behaviour when the source and destination memory regions overlap.

If you pass invalid arguments, it can crash and cause unexpected behaviour. And also it can cause undefined behaviour if the source and destination memory regions are null.

Syntax

Following is the Syntax of the C++ cstring memmove() function −

void *memmove(void *destination, const void *source, size_t num);

Parameters

Following are the parameters of this function −

  • destination: Pointer to the destination array where the content is to be moved.

  • source: Pointer to the source of data to be moved.

  • num: Number of bytes to move.

Return Value

The memmove() function returns a pointer to the destination, which is the same as the destination pointer passed as the first argument.

Example 1

In this example, we will move the content of one array to another array using the memmove() function. For this, we will create two arrays, one source array and one destination array.

#include <iostream>
#include <cstring>

using namespace std;

int main() {
   char source[] = "Hello, World!";
   char destination[100];
   
   // Moving the content of source array to destination array
   memmove(destination, source, strlen(source) + 1);
   
   cout << "Source: " << source << endl;
   cout << "Destination: " << destination << endl;
   
   return 0;
}

Output

When you run the program, the output will be:

Source: Hello, World!
Destination: Hello, World!

Example 2

Now, let's use a struct to move the content of one structure to another structure using the memmove() function.

#include <iostream>
#include <cstring>

using namespace std;

struct Employee {
   char name[50];
   int age;
   float salary;
};

int main() {
   struct Employee source = {"Ichigo Kurasaki", 30, 50000.0};
   struct Employee destination;
   
   // Moving the content of source structure to destination structure
   memmove(&destination, &source, sizeof(source));
   
   cout << "Source: " << source.name << ", " << source.age << ", " << source.salary << endl;
   cout << "Destination: " << destination.name << ", " << destination.age << ", " << destination.salary << endl;
   
   return 0;
}

Output

When you run the program, the output will be −

Source: John Doe, 30, 50000.00
Destination: John Doe, 30, 50000.00
Advertisements