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.


# 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;


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.

Contribute your code and comments through Disqus.

Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

C Programming - How do you pass a function as a parameter in C?


A prototype for a function which takes a function parameter looks like the following:

void func ( void (*f)(int) );

This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:

void print ( int x ) {
  printf("%d\n", x);

Function Call

When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:


would call func, passing the print function to it.

Function Body

As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:

for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {

Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:

void func ( void (*f)(int) ) {
  for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {

Ref : https://bit.ly/3skw9Um