memcpy() function in C++

In this guide, you will learn what is memcpy() function is in C++ programming and how to use it with an example.

1. memcpy() Function Overview

The memcpy() function is used to copy memory from one location to another. It is particularly useful for copying blocks of memory, and is a part of the C++ <cstring> header. This function is essential when working with arrays, structures, or any other data structures where raw memory copying is desired.

Signature:

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

Parameters:

- dest: Pointer to the destination memory location.

- src: Pointer to the source memory location.

- n: Number of bytes to copy.

2. Source Code Example

#include <iostream>
#include <cstring>

int main() {
    char source[] = "C++ Programming";
    char destination[50];

    // Using memcpy to copy string
    memcpy(destination, source, strlen(source) + 1); // +1 to copy the null-terminator

    std::cout << "Source string: " << source << std::endl;
    std::cout << "Destination string after memcpy: " << destination << std::endl;

    return 0;
}

Output:

Source string: C++ Programming
Destination string after memcpy: C++ Programming

3. Explanation

1. We include the required header files: <iostream> for input/output procedures and <cstring> for memcpy() and strlen().

2. We define two character arrays: source and destination.

3. We then use memcpy() to copy the content from source to destination.

4. The size parameter is determined using strlen(source) + 1 to ensure the null terminator is also copied.

5. Finally, we print out both the source and destination strings.


Comments