C Programming

How to Copy Arrays with memmove() in C Programming

Arrays are a basic element in the C programming language, which enables a programmer to store numerous items of the same data type in a single variable. There are times when a programmer may need to replicate the contents of one array to another.

What is the memmove() Function

The C library function memmove() is used to copy a certain number of bytes from one memory address to another. Due to the fact that it is unaffected by overlapping data areas, it is an effective and productive technique of copying data. When using memmove() to copy an array, there are a few things to keep in mind. The function must first be given two pointers, one representing the source memory location and the other the destination memory location. The quantity of bytes that you want to copy from the source to the destination must also be specified.

The memmove() method is a flexible function that can handle overlapping sources and copy data in any order from anywhere in memory. The only drawback is that it takes a little bit longer than other copying methods like memcpy().

How to Copy Arrays with memmove() in C Programming

The memmove() function is defined in the <string.h> library and has the syntax:

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

The pointer void* dest specifies the destination array, to which the contents of the source array will be copied. The pointer to the source array that we want to copy is const void* src. The number of bytes that we want to copy from the source array to the destination array is specified by the argument size_t n.

Have a look at the following line of code, for instance:

#include <stdio.h>

#include <string.h>

  int main() {

  int source_array[] = {1, 2, 3, 4, 5};

int destination_array[5] = {0};

size_t size = sizeof(source_array);

memmove(destination_array, source_array, size);

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

printf("%d ", destination_array[i]);

}

return 0;

}

The source array and destination array arrays are first defined in the code above. The destination array is initially empty, but the source array has elements 1 through 5. The sizeof() operator is then used to determine the size of the source array, and the result is saved in the size variable. The source array’s contents are copied across to the destination array.

Output

Conclusion

The C programming language offers an effective and dependable way to copy arrays with the memmove() function. Its versatility comes from its ability to handle overlapping memory, and because of its straightforward syntax, any C project can use it.

About the author

Hiba Shafqat

I am a Computer Science student and a committed technical writer by choice. It is a great pleasure to share my knowledge with the world in which I have academic expertise.