C++ std::memmove
Move the remaining characters left within the same buffer using an operation that supports overlapping ranges.
A simple example
std::memmove
- Start with "xAB" in a writable buffer
- Do this Move AB and the terminator one place left
- Result "AB"
Syntax
std::memmove(code, code + 3, count)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonRemove a printed prefix from a package code
A printed scanner code may begin with a standard prefix. Remove it only under the intended matching rule so the same letters inside the actual identifier are preserved.
#include <cstring>
#include <cstdio>
int main() {
char code[] = "PK-482";
std::memmove(code, code + 3, std::strlen(code + 3) + 1);
std::puts(code);
return 0;
}
482
Copying four bytes includes the three digits and the terminating null byte.
Shift a label one byte
A badge printer makes room for an extra prefix during a buffer edit. Copy the first three bytes one position to the right in the same buffer. Which four bytes remain at the start?
Shift a strip of sensor data
A display moves three occupied positions over by one. Copy the first three bytes one position to the right in the same buffer. Which four bytes remain at the start?
What to watch for
Confirm the prefix length and array bounds first. memcpy is unsuitable for overlapping ranges.