##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# memcpy

From cppreference.com
< c‎ | string‎ | byte

Defined in header `<string.h>` |  |
void* memcpy( void *dest, const void *src, size_t count ); |  | (until C99)
void* memcpy( void *restrict dest, const void *restrict src, size_t count ); |  | (since C99)

Copies `count` characters from the object pointed to by `src` to the object pointed to by `dest`. If the objects overlap, the behavior is undefined.

### [edit] Parameters

dest | - | pointer to the memory location to copy to
src | - | pointer to the memory location to copy from
count | - | number of bytes to copy

### [edit] Return value

`dest`

### [edit] Example

Run this code

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

    #define LENGTH_STRING 20

    int main()
    {
        char source[LENGTH_STRING] = "Hello, world!";
        char target[LENGTH_STRING] = "";
        int integer[LENGTH_STRING / 4] = {0};
        int i = 0;
        printf("source: %s\n", source);
        printf("target: %s\n", target);
        printf("integer: ");
        for (i = 0; i < sizeof(integer) / sizeof(integer[0]); ++i) {
            printf("%x ", integer[i]);
        }
        printf("\n");
        printf("========\n");

        /* length + 1 for the string's end-char '\0' */
        memcpy(target, source, strlen(source) + 1);
        memcpy((char *)integer, source, strlen(source));
        printf("source: %s\n", source);
        printf("target: %s\n", target);
        printf("source(hex): ");
        for (i = 0; i < sizeof(source) / sizeof(source[0]); ++i) {
            printf("%2x ", source[i]);
        }
        printf("\n");
        printf("integer(hex: little-endian): ");
        for (i = 0; i < sizeof(integer) / sizeof(integer[0]); ++i) {
            printf("%x ", integer[i]);
        }
        printf("\n");
        return 0;
    }

Output:

    source: Hello, world!
    target:
    integer: 0 0 0 0 0
    ========
    source: Hello, world!
    target: Hello, world!
    source(hex): 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0 0 0 0 0 0 0
    integer(hex, little-endian): 6c6c6548 77202c6f 646c726f 21 0

### [edit] See also

memmove | moves one buffer to another (function) [edit]
C++ documentation for memcpy

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=c/string/byte/memcpy&oldid=62616"