C Array removal with memmove
Remove the item at a chosen position from a packing list.
A simple example
Array removal with memmove
- Start with A, B, C
- Do this Remove the middle item
- Result A, C
Syntax
memmove(items + i, items + i + 1, bytes)
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonTake a cancelled item off a packing list
A customer cancels the second item on an order after the packing list has printed. The picker uses its position to remove exactly that item and reads the removed label back to the customer.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *items[] = {"Tea", "Soap", "Rice"};
size_t used = 3, index = 1;
if (index < used) {
const char *removed = items[index];
memmove(items + index, items + index + 1, (used - index - 1) * sizeof items[0]);
--used;
puts(removed);
}
return 0;
}
Soap
Soap is the item removed from the second position.
Prepare the next workshop roster
A teacher reads a workshop roster in arrival order. The middle entry cancels and is removed from the plan. Which two entries still appear, in order?
Work from the delivery round
A courier has three labelled stops in route order. The middle entry cancels and is removed from the plan. Which two entries still appear, in order?
What to watch for
C arrays have fixed capacity. Track the used length separately and move only the occupied tail after a valid index.