Namespaces
Variants
Views
Actions

memcpy

From cppreference.com
< c‎ | string‎ | byte
Revision as of 06:47, 13 November 2012 by P12 (Talk | contribs)

Defined in header <string.h>
void* memcpy( void* dest, const void* src, size_t count );

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.

Contents

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

Return value

dest

Example

#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

See also

Template:c/string/byte/dcl list memmove