bhylu.com

Advertisements

C Structure Pointers

Update one reading through a validated structure pointer and use the arrow member operator.

How it works

The arrow operator accesses a member through a pointer to a structure. p->field is equivalent to (*p).field. It does not check p for null or prove that the record remains alive. A helper taking a record pointer should state whether it reads, modifies or owns the record. In this example the helper borrows one mutable record and returns a status. It does not allocate, retain or release storage, making the lifetime responsibility clear to its caller.

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 record-pointers.c -o lesson

On 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

C17 · record-pointers.c

#include <stdio.h>
#include <stdbool.h>

struct Reading { int id; int depth; };
static bool set_depth(struct Reading *reading, int depth) {
    if (reading == NULL || depth < 0 || depth > 500) { return false; }
    reading->depth = depth;
    return true;
}

int main(void) {
    struct Reading reading = {7, 18};
    if (!set_depth(&reading, 25)) { return 1; }
    printf("Station %d: %d mm\n", reading.id, reading.depth);
    return 0;
}

Expected result

Station 7: 25 mm

The caller passes the address of its initialized record. The helper checks both pointer absence and the domain range before changing the depth. The station identifier remains unchanged. A read-only helper should take const struct Reading * instead. This pattern can evolve into a public API, but null validation alone cannot make a stale address safe.

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.

Advertisements