Skip to content

Zig Pointers

Every variable lives somewhere in memory, and that place has an address. A pointer is a value that holds such an address. Instead of copying a value around, you can hand out a pointer to it, so other code can read or change the original. You already used pointers in Zig Function Parameters to let a function change your variable. Now let’s look at them properly. If C pointers scared you once, good news: Zig’s are simpler and much harder to get wrong.

Put & in front of a variable to get its address. To get to the value a pointer points at, write .* after it:

const std = @import("std");
pub fn main() void {
var age: u32 = 30;
const ptr = &age;
std.debug.print("type: {}\n", .{@TypeOf(ptr)});
std.debug.print("value through the pointer: {d}\n", .{ptr.*});
ptr.* += 1;
std.debug.print("age is now {d}\n", .{age});
}

Output:

type: *u32
value through the pointer: 30
age is now 31
  • &age is “the address of age”. Its type is *u32, read as “pointer to a u32”.
  • ptr.* is “the thing ptr points at”. Reading it gives 30.
  • ptr.* += 1; changes the value at that address, which is age. So age becomes 31.

There’s only one variable here. ptr is just another way to reach it.

*const T: a pointer you can only read through

Section titled “*const T: a pointer you can only read through”

Take the address of a const, and you get a *const pointer. You can read through it, but not write:

const std = @import("std");
pub fn main() void {
const limit: u32 = 5;
const p = &limit;
std.debug.print("{}\n", .{@TypeOf(p)});
var level: u32 = 1;
const view: *const u32 = &level;
level = 2;
std.debug.print("view sees {d}\n", .{view.*});
}

Output:

*const u32
view sees 2

You can also choose a *const pointer on purpose, even to a var, like view here. It’s a promise: “through this pointer, I’ll only look”. The variable can still change by other means, and view sees the new value. Try to write through it, and the build fails:

pub fn main() void {
var age: u32 = 30;
const ro: *const u32 = &age;
ro.* = 31;
}
main.zig:4:7: error: cannot assign to constant
ro.* = 31;
~~^~

A *u32 turns into a *const u32 automatically when needed (you’re only giving up rights), but never the other way. That’s the rule you met as cast discards const qualifier in the last lessons.

Two different things can be const or var here, and it helps to keep them apart:

  • Whether you can change the value depends on the pointer type: *u32 yes, *const u32 no.
  • Whether you can make the pointer point somewhere else depends on whether the pointer variable is a var or a const.
const std = @import("std");
pub fn main() void {
var a: u32 = 1;
var b: u32 = 2;
var current: *u32 = &a;
current.* = 10;
current = &b;
current.* = 20;
std.debug.print("a = {d}, b = {d}\n", .{ a, b });
std.debug.print("points at b: {}\n", .{current == &b});
}

Output:

a = 10, b = 20
points at b: true

current is a var, so it can move from a to b. In the first example ptr was a const, but ptr.* += 1 still worked: the pointer stayed put, and only the value changed. Most of the time you’ll write const p = &x;, because pointers rarely need to move. == on two pointers asks “do they point at the same place?”, not “are the values equal?”.

& on an array gives you a pointer to the whole array, with the length built into the type. You can index it and ask for .len just like the array itself. You can also point at a single item:

const std = @import("std");
pub fn main() void {
var scores = [_]u32{ 10, 20, 30 };
const p = &scores;
std.debug.print("{}\n", .{@TypeOf(p)});
p[1] = 25;
std.debug.print("len {d}: {any}\n", .{ p.len, scores });
const second = &scores[1];
second.* += 100;
std.debug.print("{} -> {any}\n", .{ @TypeOf(second), scores });
}

Output:

*[3]u32
len 3: { 10, 25, 30 }
*u32 -> { 10, 125, 30 }

*[3]u32 is “pointer to an array of 3 u32”. Notice you write p[1], not p.*[1]: Zig follows the pointer for you when you index. The same thing happens with struct fields later: p.name works on a pointer to a struct. A pointer to an array also turns into a slice when a function asks for one, which is why total(&scores) worked in the parameters lesson.

A single-item pointer *T points at exactly one value. Two things you might know from C aren’t allowed on it.

No arithmetic. You can’t move it to “the next item” with + 1:

pub fn main() void {
var age: u32 = 30;
const p = &age;
const q = p + 1;
_ = q;
}
main.zig:4:17: error: incompatible types: '*u32' and 'comptime_int'
const q = p + 1;
~~^~~

There’s nothing after a single u32, so moving past it makes no sense. For pointers to several items in a row, Zig has separate types: slices (most of the time) and many-item pointers.

No null. A *T always points at something real:

pub fn main() void {
var p: *u32 = null;
_ = &p;
}
main.zig:2:19: error: expected type '*u32', found '@TypeOf(null)'
var p: *u32 = null;
^~~~

In C, any pointer can be NULL, and forgetting to check is one of the most common crashes there is. In Zig, a pointer that might be missing has a different type, ?*u32, and the compiler makes you check it before use. You’ll learn that in Zig Optionals.

A pointer is only valid while the thing it points at still exists. A function’s local variables disappear when the function returns, so a pointer to one is left pointing at nothing. That’s called a dangling pointer. Zig catches the obvious case:

const std = @import("std");
fn makeNumber() *u32 {
var n: u32 = 42;
return &n;
}
pub fn main() void {
const p = makeNumber();
std.debug.print("{d}\n", .{p.*});
}
main.zig:5:13: error: returning address of expired local variable 'n'
return &n;
^
main.zig:4:9: note: declared runtime-known here
var n: u32 = 42;
^

But it can’t catch every case. Hide the same mistake behind one more step, and it builds:

const std = @import("std");
fn makeName() []const u8 {
var buf: [5]u8 = undefined;
@memcpy(&buf, "hello");
const s: []const u8 = &buf;
return s;
}
pub fn main() void {
std.debug.print("{s}\n", .{makeName()});
}

When we ran this, it printed a few garbage bytes instead of hello. With other settings it may print hello by luck, which is worse, because the bug hides. buf lived inside makeName, and that memory gets reused as soon as the function returns.

{*} prints a pointer’s address, which can be handy when you’re debugging:

const std = @import("std");
pub fn main() void {
var x: u32 = 1;
std.debug.print("{*}\n", .{&x});
x += 1;
}

You’ll see something like:

u32@7ffe50a97db4

The type, an @, and the address in hex. The address is different on every run, so don’t rely on it for anything. The language reference on pointers lists every kind of pointer and what it supports.

Write bump(counter: *u32) void that adds 1 to the counter. Call it three times on a variable and print the result.

Hint: inside, write counter.* += 1;. At the call, pass &clicks.

Show solution
const std = @import("std");
fn bump(counter: *u32) void {
counter.* += 1;
}
pub fn main() void {
var clicks: u32 = 0;
bump(&clicks);
bump(&clicks);
bump(&clicks);
std.debug.print("clicks: {d}\n", .{clicks});
}

Output:

clicks: 3

clicks must be a var. With const clicks, &clicks would be a *const u32, and bump wouldn’t accept it.

Write larger(a: *i32, b: *i32) *i32 that returns a pointer to whichever value is bigger. Then use it to set the bigger of x = 7 and y = 12 to 0, in one line.

Hint: compare a.* and b.*, and return a or b (the pointers, not the values). The call can be followed by .* = 0.

Show solution
const std = @import("std");
fn larger(a: *i32, b: *i32) *i32 {
return if (a.* > b.*) a else b;
}
pub fn main() void {
var x: i32 = 7;
var y: i32 = 12;
larger(&x, &y).* = 0;
std.debug.print("x = {d}, y = {d}\n", .{ x, y });
}

Output:

x = 7, y = 0

Returning a pointer here is fine: it points at x or y, which live in main and still exist after larger returns.

Write doubleAll(nums: *[4]i32) void that doubles every item. Use it on { 1, 2, 3, 4 }.

Hint: for (nums) |*n| n.* *= 2; works on a pointer to an array.

Show solution
const std = @import("std");
fn doubleAll(nums: *[4]i32) void {
for (nums) |*n| n.* *= 2;
}
pub fn main() void {
var nums = [_]i32{ 1, 2, 3, 4 };
doubleAll(&nums);
std.debug.print("{any}\n", .{nums});
}

Output:

{ 2, 4, 6, 8 }

This only accepts arrays of exactly 4 items. A slice parameter ([]i32) would accept any length, which is why slices are more common. That’s coming up in Zig Slices.

  • &x gives the address of x; its type is *T. ptr.* reads or writes the value it points at.
  • A pointer to a const is a *const T: read-only. *T turns into *const T automatically, never the reverse.
  • The pointer type decides whether you can change the value; the pointer variable (var or const) decides whether it can point elsewhere.
  • &array gives a *[N]T that you can index and loop over; &array[i] points at one item.
  • A *T has no arithmetic and is never null (use ?*T for “maybe a pointer”).
  • Never return a pointer to a local variable: Zig catches the simple case, not all of them.

Next up: Zig Many-Item Pointers, pointers to an unknown number of items, and why you’ll usually prefer slices.

Quick check

1. With var n: i32 = 1; const p = &n;, what does p.* = 5; do?
2. What is the type of &limit when limit is declared with const limit: u32 = 5;?
3. Can a Zig *u32 be null?
4. A function returns &n where n is one of its local variables. What does Zig 0.17 do?