C Array indexing and element count
Read one name from an ordered roster after checking its length.
A simple example
Array indexing and element count
- Start with A, B, C
- Do this Read the second element
- Result B
Syntax
names[index]
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
./lessonRead the second name on the pickup roster
A teacher calls children in their recorded pickup order. The office asks for the second name on the roster, so the teacher checks that the list contains at least two entries before reading it.
#include <stdio.h>
int main(void) {
const char *names[] = {"Asha", "Mira", "Sam"};
size_t count = sizeof names / sizeof names[0];
if (count >= 2) puts(names[1]);
return 0;
}
Mira
Mira occupies the second position on the three-person roster.
Prepare the next workshop roster
A teacher reads a workshop roster in arrival order. Who or what occupies the second position? Count from the front of the list.
Work from the delivery round
A courier has three labelled stops in route order. Who or what occupies the second position? Count from the front of the list.
What to watch for
Calculate the count on the array itself. A helper receiving a pointer must also receive the count.