C Array bounds guard
Check the position before reading an array because C performs no automatic bounds check.
A simple example
Array bounds guard
- Start with A list containing only A
- Do this Ask for the third item
- Result Outside the list
Syntax
index < seat_count
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
./lessonFind a seat after the coach changes
A bus operator replaces a coach with a smaller one. A passenger's saved seat position now falls outside the new seating list, so the booking screen must ask them to choose again.
#include <stdio.h>
int main(void) {
const char *seats[] = {"Window", "Aisle"};
size_t seat_count = sizeof seats / sizeof seats[0];
size_t index = 2;
puts(index < seat_count ? seats[index] : "Choose another seat");
return 0;
}
Choose another seat
The saved position is just beyond the two-seat list. The booking desk asks for a replacement seat.
Open the last appointment
A desk offers two appointments and a visitor selects index one. Look up the zero-based slot. Ask the user to choose again if that position falls outside the available list.
Reject a stale bus selection
An old menu points to index two after the coach list shrinks to two stops. Look up the zero-based slot. Ask the user to choose again if that position falls outside the available list.
What to watch for
The sizeof calculation works on the array itself. Pass the count separately when a function receives a pointer.