C Array range with start and length
Read the middle batch of an order queue using a range.
A simple example
Array range with start and length
- Start with A, B, C
- Do this Select the first two items
- Result A, B
Syntax
orders[start + offset]
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
./lessonSelect two orders for the packing bench
A packing bench takes a small batch from the middle of the day's queue. The supervisor wants orders B and C on this bench while the other orders stay visible in the full queue.
#include <stdio.h>
int main(void) {
const char *orders[] = {"A", "B", "C", "D"};
size_t count = sizeof orders / sizeof orders[0];
size_t start = 1, length = 2;
if (start <= count && length <= count - start) {
for (size_t i = 0; i < length; ++i) {
printf("%s%s", i ? ", " : "", orders[start + i]);
}
}
return 0;
}
B, C
The requested range contains only orders B and C.
Prepare the next workshop roster
A teacher reads a workshop roster in arrival order. The coordinator prints the first two entries on a separate slip. Which entries appear, in order?
Work from the delivery round
A courier has three labelled stops in route order. The coordinator prints the first two entries on a separate slip. Which entries appear, in order?
What to watch for
C does not store the length in a pointer. Validate the range against the element count before reading.