Zig Pointers
A pointer holds the memory address of a value instead of the value itself. Pointers let a function change its caller's variables, let several parts of a program share one piece of data, and avoid copying large structures. Zig's pointers are like C's, but safer: they can't be null unless declared optional, and there are separate types for "one item" and "many items".
Taking an address and dereferencing
&x gives the address of x. If p is a pointer, p.* is the value it points to:
const std = @import("std");
pub fn main() void {
var score: u32 = 10;
const ptr: *u32 = &score;
ptr.* += 5; // change score through the pointer
std.debug.print("score = {d}\n", .{score});
std.debug.print("through pointer = {d}\n", .{ptr.*});
std.debug.print("type: {s}\n", .{@typeName(@TypeOf(ptr))});
}score = 15
through pointer = 15
type: *u32
| Syntax | Meaning |
|---|---|
*T |
pointer to one mutable T |
*const T |
pointer to one T that may not be changed through it |
&x |
address of x |
p.* |
the value p points to |
?*T |
optional pointer (may be null) |
const pointers
The address of a const variable is a *const T: you can read through it but not write. A *T converts to *const T automatically, never the other way around.
const limit: u32 = 100;
const p = &limit; // *const u32
// p.* = 5; // error: cannot assign to constantChanging the caller's variables
Function parameters are copies and read-only. To let a function modify something, pass a pointer:
const std = @import("std");
fn swap(a: *i32, b: *i32) void {
const tmp = a.*;
a.* = b.*;
b.* = tmp;
}
fn resetAll(values: []i32) void {
for (values) |*v| v.* = 0;
}
pub fn main() void {
var x: i32 = 1;
var y: i32 = 2;
swap(&x, &y);
std.debug.print("x={d} y={d}\n", .{ x, y });
var data = [_]i32{ 5, 6, 7 };
resetAll(&data);
std.debug.print("{any}\n", .{data});
}x=2 y=1
{ 0, 0, 0 }
Pointers to structs
Field access works directly through a pointer — no -> like in C. p.field is the same as p.*.field:
const std = @import("std");
const Player = struct {
name: []const u8,
hp: u32,
level: u8,
};
fn levelUp(p: *Player) void {
p.level += 1;
p.hp += 10;
}
pub fn main() void {
var hero = Player{ .name = "Kai", .hp = 100, .level = 1 };
const ptr = &hero;
levelUp(ptr);
levelUp(&hero);
std.debug.print("{s}: level {d}, hp {d}\n", .{ ptr.name, hero.level, ptr.*.hp });
}Kai: level 3, hp 120
Pointers to array elements
You can point at a single element of an array, and loop with pointer captures to update elements:
const std = @import("std");
pub fn main() void {
var levels = [_]u8{ 3, 7, 1 };
const middle = &levels[1];
middle.* = 9;
for (&levels) |*lvl| lvl.* *|= 30; // saturating multiply in place
std.debug.print("{any}\n", .{levels});
const arr_ptr = &levels; // *[3]u8: pointer to the whole array
std.debug.print("len via pointer: {d}, first: {d}\n", .{ arr_ptr.len, arr_ptr[0] });
}{ 90, 255, 30 }
len via pointer: 3, first: 90
A pointer to an array (*[3]u8) knows the length and can be indexed; it converts to a slice automatically.
Dangling pointers
Zig does not track lifetimes the way Rust does. A pointer to a local variable becomes invalid when the function returns. Returning one compiles but is a bug:
fn bad() *u32 {
var local: u32 = 5;
return &local; // the memory is reused after return!
}The fix is to return the value itself, take a pointer to memory the caller owns, or allocate on the heap with an allocator.
Pointer kinds at a glance
| Type | Points to | Length known? |
|---|---|---|
*T |
exactly one item | — |
*[N]T |
an array of N items | yes, at compile time |
[]T |
a slice (pointer + length) | yes, at runtime |
[*]T |
an unknown number of items | no |
[*:0]T |
items ending with a 0 sentinel | found by scanning |
The last two are the subject of the next lesson.
Tip: In everyday Zig, you mostly use
*Tfor "modify this" and slices for "many of these". Raw many-item pointers are for C interop and low-level code.
Test yourself
If p is a *i32, how do you add 1 to the value it points to?
- *p += 1
- p += 1
- p.* += 1
- p->value += 1
What type does &x have when x is declared with const x: u8 = 1;?
- *u8
- *const u8
- ?*u8
- []u8
With p: *Player, how do you read the hp field?
- p->hp
- p.hp
- (*p).hp only
- p[hp]