TExcelTAD
Home › Zig › Zig Many-item Pointers & Sentinels

Zig Many-item Pointers & Sentinels

Slices are Zig's everyday way to refer to "several items". Underneath, a slice is a many-item pointer plus a length. This lesson looks at those raw many-item pointers and at sentinel-terminated types — arrays, slices and pointers whose end is marked by a special value, like the zero byte at the end of every C string.

Many-item pointers: [*]T

A [*]T points to the first of an unknown number of Ts. It supports indexing and pointer arithmetic, but it has no length, so Zig cannot check bounds — just like a C pointer.

zig · try it yourself
const std = @import("std");

pub fn main() void {
    var buffer = [_]u16{ 100, 200, 300, 400, 500 };
    const many: [*]u16 = &buffer; // array pointer coerces to [*]T

    std.debug.print("many[2] = {d}\n", .{many[2]});

    const shifted = many + 3; // pointer arithmetic
    std.debug.print("shifted[0] = {d}\n", .{shifted[0]});

    // give it a length again by slicing it
    const s: []u16 = many[1..4];
    std.debug.print("slice: {any} (len {d})\n", .{ s, s.len });
}
many[2] = 300
shifted[0] = 400
slice: { 200, 300, 400 } (len 3)
Operation *T [*]T []T
p.* yes no no
p[i] no yes (unchecked) yes (checked)
p + n no yes no
p[a..b] no yes → slice yes → slice
.len no no yes

As soon as you know the length, slice the pointer (p[0..len]) and work with the slice: you get bounds checking back for free.

Sentinels

A sentinel is a value that marks the end of a sequence. C strings end with a 0 byte; many APIs end lists with a null pointer. Zig puts the sentinel into the type with :value:

Type Meaning
[N:0]u8 array of N bytes, followed by a 0 byte
[:0]const u8 slice whose element at index len is 0
[*:0]const u8 many-item pointer ending at a 0 byte — a C string

String literals are sentinel-terminated arrays, which is why their type is *const [N:0]u8:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const word = "zig";
    std.debug.print("type: {s}\n", .{@typeName(@TypeOf(word))});
    std.debug.print("len: {d}, byte after the end: {d}\n", .{ word.len, word[word.len] });

    const as_slice: [:0]const u8 = word;
    const as_c_string: [*:0]const u8 = word;
    std.debug.print("{s} {s}\n", .{ as_slice, as_c_string });
}
type: *const [3:0]u8
len: 3, byte after the end: 0
zig zig

The sentinel is not counted in .len, but it may be read at index len. Any sentinel value works, not only 0: [:255]u8 or [*:null]?*T are valid too.

Finding the length: std.mem.span

A [*:0]const u8 doesn't store its length, but because the end is marked, Zig can find it by scanning. std.mem.span does exactly that and returns a proper slice, and std.mem.len returns just the count:

zig · try it yourself
const std = @import("std");

// imagine this pointer came from a C library
fn getGreeting() [*:0]const u8 {
    return "hello from C-land";
}

pub fn main() void {
    const raw = getGreeting();
    std.debug.print("length by scanning: {d}\n", .{std.mem.len(raw)});

    const s = std.mem.span(raw); // [:0]const u8
    std.debug.print("slice: {s}, len {d}\n", .{ s, s.len });

    var words = std.mem.tokenizeScalar(u8, s, ' ');
    while (words.next()) |w| std.debug.print("[{s}]", .{w});
    std.debug.print("\n", .{});
}
length by scanning: 17
slice: hello from C-land, len 17
[hello][from][C-land]

Sentinel slices of your own data

Slicing with buf[a..b :0] creates a sentinel-terminated slice — Zig checks (in safe builds) that buf[b] really holds the sentinel. This is how you prepare a buffer for a C function that wants a zero-terminated string:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    var buf: [32]u8 = undefined;
    const name = "config.ini";
    @memcpy(buf[0..name.len], name);
    buf[name.len] = 0; // write the terminator

    const c_str: [:0]const u8 = buf[0..name.len :0];
    std.debug.print("{s} ({d} bytes + terminator)\n", .{ c_str, c_str.len });
}
config.ini (10 bytes + terminator)

std.fmt.bufPrintZ and allocator.dupeZ also produce zero-terminated strings directly.

When to use what

You have… Use
ordinary Zig data with a length []T / []const T
a fixed-size buffer [N]T
a string to pass to C [*:0]const u8 (or [:0]const u8)
a pointer from C with a separate length [*]T, then slice it p[0..len]
a C pointer that may be null ?[*]T / ?[*:0]const u8

Note: C header translations use the type [*c]T ("C pointer"), which can be null and act as either a single or many-item pointer. It exists only for C interop; convert it to a proper Zig type as soon as you can.

Test yourself

What is missing from a [*]T compared to a []T?

  1. The pointer
  2. The length
  3. The element type
  4. Mutability

What is the type of the literal "abc"?

  1. []const u8
  2. *const [3:0]u8
  3. [3]u8
  4. [*]u8

What does std.mem.span(p) do for p: [*:0]const u8?

  1. Allocates a copy
  2. Scans for the sentinel and returns a slice
  3. Returns the capacity
  4. Frees the pointer