Course contentsShow
← C
Lesson 856 of 1,21912. The Standard LibraryFree lesson

Copying memory with `memcpy`

Copying memory with memcpy

What you'll learn: How to use the memcpy function to efficiently duplicate a raw block of data from one location to another.

The Digital Photocopy

Up until now, you have likely used the assignment operator (=) to copy values like integers or characters. However, when you deal with large chunks of memory—like an entire array or a complex structure—you need a more heavy-duty tool.

Think of memcpy (memory copy) as a high-speed industrial photocopier. Instead of copying one item at a time, it looks at a specific starting address, counts out a certain number of bytes, and reproduces that exact sequence at a new destination. It doesn't care if the memory represents numbers, text, or pixels; it just moves the raw bits.

How it Works

The function is found in the <string.h> library and follows this pattern: memcpy(destination, source, size_in_bytes);

  1. Destination: The address where you want the data to go.
  2. Source: The address where the data currently lives.
  3. Size: Exactly how many bytes to move.

Because memcpy works with "void pointers," it is type-agnostic. It treats everything as a simple bucket of bytes.

A Concrete Example

Imagine you have an array representing a high-score table and you want to create a backup. Instead of writing a loop to copy every individual element, you can copy the whole block in one go.

#include <stdio.h>
#include <string.h>

int main() {
    int original_scores[5] = {1050, 2200, 890, 4500, 310};
    int backup_scores[5];

    // Calculate the total bytes: (number of elements * size of one element)
    size_t total_bytes = sizeof(original_scores);

    // Copy the entire block from original to backup
    memcpy(backup_scores, original_scores, total_bytes);

    // Testing the result
    printf("Backup's third score: %d\n", backup_scores[2]); // Outputs 890

    return 0;
}

Important Safety Tip

The memcpy function is built for speed, which means it doesn't have "safety rails." It assumes you have already allocated enough space at the destination. If you try to copy 100 bytes into a destination that only has room for 50, memcpy will keep writing anyway, potentially crashing your program or corrupting other data. Always double-check your sizeof calculations!

Key takeaway

Use memcpy to rapidly duplicate blocks of memory by specifying the source, destination, and the total number of bytes to transfer.