Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Types and Memory

Pointers

Understand Zig pointers: *T single-item pointers, address-of and dereference, const pointers, many-item [*]T, slices vs pointers, optional pointers, alignment and dangling pointer risks.

A pointer holds the address of a value in memory. Zig pointers are what C pointers should have been: the type tells you whether you point at one item or many, whether you may write through it, and whether it can be null. The compiler checks all of that, so most pointer mistakes become compile errors instead of crashes.

Single-item pointers: *T

&x takes the address of x, producing a *T. ptr.* follows the pointer to the value.

ZIG
const std = @import("std");

pub fn main() void {
    var score: u32 = 10;
    const ptr: *u32 = &score;

    ptr.* += 5;                    // write through the pointer
    std.debug.print("score = {d}\n", .{score});
    std.debug.print("via ptr = {d}\n", .{ptr.*});
}
TEXT
score = 15
via ptr = 15

The postfix .* reads naturally left to right: ptr.*.field is "the field of what ptr points to". In practice you rarely write it for structs, because field access auto-dereferences: if p is a *Point, p.x just works.

Pointer to constant: *const T

Taking the address of a const gives a pointer that cannot write:

ZIG
const limit: u32 = 100;
const p: *const u32 = &limit;
// p.* = 5;     // error: cannot assign to constant

*const T is the default choice for read-only access. A *T converts to *const T implicitly, never the other way. Function parameters that only read through a pointer should say *const T, which documents intent and accepts both kinds.

Modifying through a parameter

Pointers are how functions change the caller's data:

ZIG
fn swap(a: *i32, b: *i32) void {
    const tmp = a.*;
    a.* = b.*;
    b.* = tmp;
}

pub fn main() void {
    var x: i32 = 1;
    var y: i32 = 2;
    swap(&x, &y);
    std.debug.print("{d} {d}\n", .{ x, y });   // 2 1
}

Pointers to arrays, slices and many-item pointers

There are four shapes you will meet; the type says which:

Type Meaning Knows its length?
*T exactly one T yes, 1
*[N]T pointer to an array of N yes, N (compile time)
[]T slice: pointer plus length yes, at runtime
[*]T many-item pointer (like C) no

*[N]T and []T convert freely in the safe direction (array pointer to slice). A [*]T has no length, indexing it is unchecked, and you only meet it when talking to C or building low-level containers. Prefer slices everywhere else.

ZIG
var numbers = [_]i32{ 1, 2, 3, 4 };
const array_ptr: *[4]i32 = &numbers;
const slice: []i32 = &numbers;              // coerces
const many: [*]i32 = &numbers;              // loses the length

array_ptr[0] = 10;
slice[1] = 20;
many[2] = 30;
// numbers == { 10, 20, 30, 4 }

Pointer arithmetic exists only on many-item pointers (many + 1) and slicing; *T does not support it, which prevents the common C error of walking past a single object.

Optional pointers: ?*T

A normal pointer can never be null. If a pointer might be absent, say so in the type with ?*T. Unwrap it before use:

ZIG
var value: i32 = 7;
var maybe: ?*i32 = &value;

if (maybe) |p| {
    p.* += 1;
}
maybe = null;

An optional pointer is the same size as a plain pointer (null is address zero), so it costs nothing. This is how Zig kills "null pointer dereference" in everyday code. The optional chapter shows orelse and .?.

Pointers to struct fields and pointer casts

&s.field points inside a struct, and @fieldParentPtr goes back from a field to its struct (used in intrusive lists). Casting between unrelated pointer types needs @ptrCast, and changing alignment needs @alignCast. These builtins are the "unsafe" doors; you will rarely open them outside systems code or C interop.

ZIG
const bytes = [_]u8{ 0x78, 0x56, 0x34, 0x12 };
const as_u32: *align(1) const u32 = @ptrCast(&bytes);
// reads 0x12345678 on a little-endian machine

Lifetimes and dangling pointers

Zig does not track how long a pointee lives. The classic bug:

ZIG
fn dangling() *i32 {
    var local: i32 = 42;
    return &local;       // BUG: local dies when the function returns
}

Some compiler versions reject this obvious case, but none can catch every indirect version of it. Rules of thumb:

  • Never return pointers or slices to locals.
  • A pointer into a growing array list becomes invalid when the list reallocates.
  • Memory freed with allocator.free must not be used again.
  • Debug allocators and tests with std.testing.allocator find use-after-free and leaks for you in the allocators chapter.

Zig has no borrow checker. Pointer correctness is partly on you, exactly as in C, but the type system narrows what can go wrong: no null by default, no arithmetic on single pointers, bounds-checked slices.

Pointer sizes and addresses

All pointers on a 64-bit machine are 8 bytes, usize-sized. @intFromPtr(p) gives the address as a usize and @ptrFromInt goes the other way; they are mainly for embedded work and debugging. Printing with {*} shows an address, which differs between runs.

Stand-ins you can run

C pointers behave the same way at runtime. The stand-in shows swapping through pointers, a many-item walk, and an explicit null check, the part Zig forces into the type.

C Stand-in (C): pointers, swap, array walk, null check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Rust Stand-in (Rust): references are non-null and const by default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you read the value a pointer p: *i32 points to?

    Zig uses the postfix dereference p.*.
  2. 2. Can a plain *u32 be null?

    Zig pointers are non-null by default; optional pointers make nullability explicit.
  3. 3. What is the difference between []T and [*]T?

    Slices know their length and are bounds-checked; many-item pointers do not.
  4. 4. Which pointer type should a function use to only read a u32 through a pointer?

    *const u32 documents read-only access and accepts both mutable and const pointers.
  5. 5. What is wrong with fn f() *i32 { var x: i32 = 1; return &x; }?

    The local's storage ends with the function, leaving a dangling pointer.

Summary

  • &x takes an address, p.* dereferences; struct field access through a pointer auto-dereferences.
  • *T writes, *const T only reads; *[N]T and []T know their length, [*]T does not.
  • Pointers are never null unless the type is ?*T.
  • Zig does not track lifetimes: avoid returning pointers to locals and using memory after it is freed.
  • Pointer casts (@ptrCast, @alignCast) are the explicit unsafe escape hatches.

Next: Structs