bhylu.com

Advertisements

C Pointers

Use a pointer to update one existing object and identify exactly what that pointer is allowed to access.

How it works

The address-of operator produces a pointer to an object. Dereferencing a valid pointer designates that object so you can read or modify it. A pointer type tells the compiler the pointed-to type, but does not prove that the address is live, aligned, in bounds or owned by the caller. This first pointer refers to a local int whose lifetime covers every use. Its numeric address is intentionally not part of the expected output because addresses vary across executions and targets.

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 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 · pointers.c

#include <stdio.h>

int main(void) {
    int depth = 18;
    int *selected = &depth;
    *selected = 22;
    printf("Depth: %d\n", depth);
    printf("Same object: %d\n", selected == &depth);
    return 0;
}

Expected result

Depth: 22
Same object: 1

selected stores the address of depth. Assignment through *selected changes depth itself rather than the pointer. The equality compares two pointers to the same object. If you display an object pointer with printf, convert it to void * and use %p; its representation is implementation-defined. Function pointers have different portability rules and should not be treated as object pointers.

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