Library contents

C Append to a bounded array

Append a new passenger to the end of a school bus register.

A simple example

Append to a bounded array

  1. Start with List containing A
  2. Do this Append B
  3. Result A, B
Appending puts the new element after the last existing element.

Syntax

C syntax
riders[used++] = name
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
./lesson

Add the last student to the bus register

Two families have already booked seats on a school bus. A third student registers at the desk, so the coordinator appends the name and checks the final passenger count before departure.

From the programconst char *riders[4] = {"Mira", "Sam"}
Result3
lesson.c
#include <stdio.h>

int main(void) {
    const char *riders[4] = {"Mira", "Sam"};
    size_t used = 2;
    if (used < sizeof riders / sizeof riders[0]) {
        riders[used++] = "Nia";
    }
    printf("%zu", used);
    return 0;
}
Output
3

The two earlier bookings keep their places and the third child brings the count to three.

Advertisements

Extend a reading list

A class has chosen one novel and adds two more titles. The desk adds the new entries after the existing ones. Read the resulting sequence in its recorded order.

GivenFern + Tide, Sky
Worked resultFern · Tide · Sky

Update an equipment checklist

A technician adds the final item after packing two pieces of equipment. The desk adds the new entries after the existing ones. Read the resulting sequence in its recorded order.

GivenLens, Stand + Cable
Worked resultLens · Stand · Cable

What to watch for

Track the used length and check capacity before appending. A full array needs more storage or an explicit full-register response.

Documentation for Append to a bounded array