C memcpy() Function Tutorial

  • Post author:
  • Post category:C

In this section, we will learn what the memcpy() function is and how it works in C.

memcpy() Function in C

There are times that we want to copy the content of one array to another in a program. This is where the `memcpy()` function can help us.

Notes:

  • The underlying type of the array for this function is irrelevant and it works with different types of arrays like `double`, `int`, `float` etc.
  • The prototype of the function is in `string.h` header file and so we need to include the file in order to use the function.

memcpy() Function Syntax

Here’s the prototype of the function:

void *memcpy(void *dest, const void * src, size_t n)

memcpy() Function Parameters

  • The first argument of the function is a pointer to the array that we want to copy the content of another array into.
  • The second argument is the pointer to the array that we want to get the content from.
  • The third argument is the number of bytes that we want to copy from the source to the destination.

For example, if we wanted to copy 10 elements of an array of type integer, we would use `10 * sizeof(int)` to get the right size.

memcpy() Function Return Value

The returned value of this function in a successful operation is the pointer to the destination array (the first argument).

Example: using memcpy() function in C

#include <stdio.h>
#include <string.h>
int main() {

    int source [] = {1,2,3,4,5,6,7};
    int size = sizeof(source)/ sizeof(int);

    int destination[size];

    memcpy(destination, source, size * sizeof(int));
    for (int i= 0 ; i<size; i++){
        printf("%d, ",destination[i]);
    }
    return 0;
}

Output:

1, 2, 3, 4, 5, 6, 7,

Leave a Reply