C memmove() Function Tutorial

  • Post author:
  • Post category:C

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

memmove() 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 `memmove()` function can help.

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.

memmove() Function Syntax

Here’s the prototype of the function:

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

memmove() Function Parameters

  • The first argument of the function is the 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.

Note: the underlying type of the array for this function is irrelevant and it works with different types of arrays like `double`, `int`, `float` etc.

memmove() 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 memmove() function in C

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

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

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

Output:

1, 2, 1, 2, 3, 4, 5, 8, 9, 10,

Difference between strcpy and memcpy Functions

When we call this function, it will copy the content of the source array into a temporary buffer first and then it will move the data from buffer to the destination array. That’s why it is safer to use this function over `memcpy()` function when we want to copy data in overlapping blocks of memory.

Leave a Reply