C Updating Arrays
Replace one suspect reading after checking its index and keep identity separate from position.
How it works
An array subscript selects one element object, so assigning through it changes that element. An index is only a position in the current layout. If readings are reordered, an old position may identify a different record. Before an update derived from outside input, validate the index against the element count. This lesson uses size_t throughout the index contract to avoid accepting a negative int and then accidentally converting it into a very large unsigned position.
Run it locally
Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.
cc -std=c17 -Wall -Wextra -Wpedantic -Werror array-updates.c -o lessonOn Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.
Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.
Example
#include <stdio.h>
int main(void) {
int depths[] = {12, 19, 16};
size_t count = sizeof depths / sizeof depths[0];
size_t position = 1;
if (position < count) { depths[position] = 17; }
for (size_t i = 0; i < count; ++i) {
printf("%zu: %d\n", i, depths[i]);
}
return 0;
}
Expected result
0: 12
1: 17
2: 16
The check happens before evaluating the selected element. Only the middle reading changes. The count remains three because assignment replaces a value without changing array storage. For a larger application, give each reading a record identifier and resolve its current position before applying an edit. A valid bound does not prove that an edit targets the right real-world reading.
For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.