w3resource

C Language: Custom memcpy() function

C - Implementing a custom memcpy() function.

The memcpy() function is used to copy n bytes from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behaviour is undefined.

Code:

# include <stdio.h>

void *my_memcpy(void *dest, const void *src, size_t n) {
    char *cdest = (char *)dest;
    const char *csrc = (const char *)src;

    for (size_t i = 0; i < n; i++) {
        cdest[i] = csrc[i];
    }
    return dest;
}

int main() {
    char src[] = "C language snippets.";
    char dest[20];
    my_memcpy(dest, src, sizeof(src));
    printf("Copied string is: %s\n", dest);
    return 0;
}

Output:

Copied string is: C language snippets.

The my_memcpy() function takes three arguments: a pointer to the destination buffer, a pointer to the source buffer, and the number of bytes to copy. It then casts the pointers to char * and const char * respectively, so that it can copy the individual bytes using a loop. Finally, it returns a pointer to the destination buffer.

Note: Here we assume that the memory areas pointed to by dest and src do not overlap; if they do overlap, the behavior is undefined.



Follow us on Facebook and Twitter for latest update.