memcpy function(Copy Memory Block) in C Language – example and detail

In the C Programming Language, the memcpy function copies n characters from the object pointed to by s2 into the object pointed to via s1. It returns a pointer to the destination.

The memcpy feature might also now not work if the objects overlap.

Syntax

The syntax for the memcpy function in the C Language is:

void *memcpy(void *s1, const void *s2, size_t n);

Parameters or Arguments

s1 An array where s2 will be copied to. s2 The string to be copied. n The number of characters to copy.

Returns

The memcpy function returns s1.

Required Header

In the C Language, the required header for the memcpy feature is:

#include <string.h>

Applies To

In the C Language, the memcpy function can be used in the following versions:

ANSI/ISO 9899-1990

memcpy Example

Let’s seem to be at an instance to see how you would use the memcpy feature in C program:

/* Example using memcpy by TechOnTheNet.com */

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

int main(int argc, const char * argv[])
{
    /* Create a place to store our results */
    int result;

    /* Create two arrays to hold our data */
    char original[50];
    char newcopy[50];

    /* Copy a string into the original array */
    strcpy(original, "C memcpy at TechOnTheNet.com");

    /* Copy the first 24 characters of the original
     array into the newcopy array */
    result = memcpy(newcopy, original, 24);

    /* Set the character at position 24 to a null (char 0)
     in the newcopy array to ensure the string is terminated
     (This is important since memcpy does not initialize memory
     and printf expects a null at the end of a string) */
    newcopy[24] = 0;

    /* Display the contents of the new copy */
    printf("%s\n", newcopy);

    return 0;
}

When compiled and run, this utility will output:

C memcpy at TechOnTheNet

Similar Functions

Other C functions that are comparable to the memcpy function:

memmove feature strcpy function strncpy feature