typestar

Pointers in Zig

A single-item pointer doubles a counter in place; .* is the dereference.

const std = @import("std");

fn double(x: *i32) void {
    // x.* reaches through the pointer to the value.
    x.* *= 2;
}

pub fn main() void {
    var count: i32 = 21;
    double(&count);
    std.debug.print("doubled in place: {d}\n", .{count});

    const ptr = &count;
    std.debug.print("read through a pointer: {d}\n", .{ptr.*});
}

How it works

  1. x: *i32 is a pointer to exactly one integer — no arithmetic, no null.
  2. x.* *= 2 writes through the pointer; &count takes the address.
  3. A const ptr can still read ptr.* — the const is on the binding.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
311
Tokens
92
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 2 of 3 in Optionals & pointers, step 11 of 27 in Language basics.

← Previous Next →

Pointers in other languages