totn C Functions

C Language: memcpy function
(Copy Memory Block)

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

The memcpy function may 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 function 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 look at an example to see how you would use the memcpy function 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 application will output:

C memcpy at TechOnTheNet

Similar Functions

Other C functions that are similar to the memcpy function: