Pointers

10.1 Pointer Types

Single-item pointer (non-null) Pointer to constant data Many-item pointer (unknown length, supports indexing and arithmetic) Pointer to an array (length known) Slice (pointer + runtime length) Sentinel-terminated many-item pointer

Optional pointer (nullable, same size as *T) C pointer (for translated C code only; avoid in Zig code) Volatile (MMIO) Pointer with a specific alignment *allowzero T

Pointer that may be address 0 (freestanding)

10.2 Using Pointers

var x: i32 = 10;
const p: *i32 = &x;
p.* = 20;                         // dereference with .*
std.debug.print("{d}\n", .{x});   // 20

const cp: *const i32 = &x;        // can read, can't write through it
_ = cp;

var arr = [_]u8{ 1, 2, 3, 4 };
const many: [*]u8 = &arr;         // many-item pointer
std.debug.print("{d}\n", .{many[2]});
const moved = many + 1;           // pointer arithmetic (only on [*]T)
_ = moved;

const Point = struct { x: i32, y: i32 };
var pt = Point{ .x = 1, .y = 2 };
const pp = &pt;
pp.x = 5;                          // field access auto-dereferences single pointers

10.3 Pointer Casting

const addr: usize = @intFromPtr(p);
const back: *i32 = @ptrFromInt(addr);
const bytes: *[4]u8 = @ptrCast(p);                 // reinterpret the pointee type
const aligned: *u32 = @ptrCast(@alignCast(raw));   // assert alignment (checked in safe mode)
const mutable: *i32 = @constCast(cp);              // remove const (dangerous)
const opaque_ptr: *anyopaque = @ptrCast(&x);
const typed: *i32 = @ptrCast(@alignCast(opaque_ptr));

10.4 Pointer Safety Notes

There's no automatic lifetime tracking. Don't return pointers to stack locals (a dangling pointer).

Pointers to elements of growable containers (ArrayList) are invalidated when the container reallocates.

Use slices instead of [*]T + length whenever possible.