In C, memmove() copies n bytes from one place to another. Unlike memcpy(), the source and destination may overlap, so it is safe for shifting bytes inside one array.
You pass the destination, the source, and the count. All three are required. The result is the destination pointer. Include <string.h>.
Syntax
Pass destination, source, and count. Start with this call.
C
memmove(buf + 1, buf, 4);
Call
What it does
memmove(buf + 1, buf, 4)
Shifts 4 bytes one place to the right inside the same array.
Include <string.h>. Prefer this over memcpy() when the regions might overlap.
Print as a string. Because the terminator was copied, %s works.
Overlap not required.memmove is still correct; memcpy would also be fine here.
Example 3 — Shift an Integer Array Right
Open a hole at index 0 by sliding elements one slot right. Copy backward-style overlap needs memmove.
C
#include <stdio.h>
#include <string.h>
int main(void) {
int a[5] = { 10, 20, 30, 40, 0 };
int i;
/* shift first 4 ints one place right */
memmove(a + 1, a, 4 * sizeof(int));
a[0] = 5;
for (i = 0; i < 5; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
Output
5 10 20 30 40
How It Works
Start. Array is {10, 20, 30, 40, 0}.
Move four ints right.memmove(a+1, a, 4*sizeof(int)) yields {10, 10, 20, 30, 40} temporarily—overlap is handled so values are not lost.
Write the new head.a[0] = 5 → {5, 10, 20, 30, 40}.
Why memmove?memcpy here would be undefined because a and a+1 overlap.
Frequently Asked Questions
memmove() copies n bytes from src to dest, even when the regions overlap.
All three are required. dest, src, and n work like memcpy, but overlap is allowed.
The same dest pointer you passed in.
Include <string.h>.
Use memmove() whenever dest and src might overlap, such as when shifting bytes in one array.