C++ example program to move a block of memory

C++ example program to move a block of memory:

header provides a method called memmove that can be used to move a block of memory pointed by a pointer to another location pointed by another pointer. We will use c-type string, i.e. character array for this example. In this post, I will show you the definition of memmove and how to use it with an example.

Definition of memmove:

memmove method is defined as like below:

void * memmove ( void * dest, const void * src, size_t num );

Here, src and dest pointers are pointing to some memory blocks. This method copies num number of bytes from the memory blocks pointed by the src pointer to the memory blocks pointed by the dest pointer. The destination and source memory blocks may overlap.

We don’t have to think about the type of data in the memory blocks. It will copy the bytes. Also it doesn’t check for any null character in the memory blocks.

It returns dest, or destination pointer.

Example or memmove:

Let’s take a look at the below example program:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char firstStr[20] = "hello World";
    char secondStr[20];

    memmove(secondStr, firstStr, 5);

    cout << "firstStr: " << firstStr << endl;
    cout << "secondStr: " << secondStr << endl;
    return 0;
}

In this example, we are using memmove to copy the first 5 bytes from firstStr to secondStr. If you run, it will give the below output:

firstStr: hello World
secondStr: hello

You might also like: