C++ program to copy from one array to another using memcpy

C++ cstring memcpy method explanation with example:

memcpy method is used to copy contents from a source to a destination. We can copy any type of data using this method. We can provide the number of bytes to copy and it will copy that amount of bytes.

In this post, I will show you how to use this method with example.

Definition of memcpy:

memcpy is defined as below:

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

It copies data from the memory blocks pointed by the src to the memory blocks pointed by the dest. It copies num amount of bytes.

It doesn’t care about the underlying data. It also doesn’t check for any terminating character in the src. It only copies the bytes.

Example of memcpy to copy a string:

Let’s use memcpy to copy a string or character array:

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

int main()
{
    char sourceStr[] = "Hello World !!";
    char destStr[50];

    memcpy(destStr, sourceStr, strlen(sourceStr) + 1);

    cout << "destStr : " << destStr << endl;
    return 0;
}

If you run this program, it will print:

destStr : Hello World !!

As you can see here, it copied the sourceStr to destStr.

Example of memcpy to copy structure:

We can also use memcpy to copy a structure. For example:

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

struct
{
    char name[10];
    int age;
} student1, student2;

int main()
{
    char name[] = "Alex";

    memcpy(student1.name, name, sizeof(name) + 1);
    student1.age = 20;

    memcpy(&student2, &student1, sizeof(student1));

    cout << "student2 : name: " << student2.name << ",Age:" << student2.age << endl;
    return 0;
}

In this example, we copied the content of student1 to student2. Both are structures. If you run it, it will print the below output:

student2 : name: Alex,Age:20

You might also like: