Zig Sentinel-Terminated Types
C doesn’t store the length of a string. Instead, it puts a zero byte after the last character, and every function that reads the string walks along until it finds that zero. Zig slices carry their length, so they don’t need that trick. But Zig talks to C all the time, so it has types for “items that end with a special value”. That value is called a sentinel, and the :0 you’ve seen in *const [3:0]u8 is one. This lesson explains what those types mean, so they stop looking scary, and how to move between them and normal slices.
The :0 in string literals
Section titled “The :0 in string literals”Ask Zig for the type of a string literal, and the sentinel shows up:
const std = @import("std");
pub fn main() void { const name = "Zig"; std.debug.print("{}\n", .{@TypeOf(name)}); std.debug.print("len {d}, byte after the end: {d}\n", .{ name.len, name[name.len] });}Output:
*const [3:0]u8len 3, byte after the end: 0[3:0]u8 means “an array of 3 bytes, followed by a 0 byte”. The :0 after the length is the sentinel. The length is still 3: the zero isn’t counted, but it’s really there in memory, and you’re even allowed to read it at index len. Zig puts it there so a string literal can be handed straight to a C function.
Sentinel arrays
Section titled “Sentinel arrays”You can make your own sentinel-terminated arrays with [N:x]T, or [_:x]T to let Zig count. The sentinel doesn’t have to be 0, though it almost always is:
const std = @import("std");
pub fn main() void { const hi = [_:0]u8{ 'h', 'i' }; std.debug.print("{}: len {d}, size {d} bytes\n", .{ @TypeOf(hi), hi.len, @sizeOf(@TypeOf(hi)) });
const readings = [_:255]u8{ 12, 40, 7 }; std.debug.print("after the last reading: {d}\n", .{readings[readings.len]});}Output:
[2:0]u8: len 2, size 3 bytesafter the last reading: 255hi has a length of 2 but takes 3 bytes, the extra one being the sentinel. readings ends with 255, a value that can mark “end of data” when 0 is a real reading. You’ll rarely need anything but 0, but it’s good to know the type isn’t only about strings. The reference covers these as sentinel-terminated arrays.
Sentinel slices: [:0]const u8
Section titled “Sentinel slices: [:0]const u8”The slice version is [:0]T: a normal slice (pointer plus length) that also promises a zero right after the last item. A sentinel slice turns into a normal slice automatically, so you can pass one anywhere a []const u8 is expected:
const std = @import("std");
fn shout(text: []const u8) void { std.debug.print("{s}!\n", .{text});}
pub fn main() void { const z: [:0]const u8 = "hello"; std.debug.print("{} with len {d}\n", .{ @TypeOf(z), z.len }); shout(z);}Output:
[:0]const u8 with len 5hello!The other direction doesn’t work. A plain slice makes no promise about what comes after its last item, so Zig won’t treat it as zero-terminated:
pub fn main() void { const plain: []const u8 = "hello"; const z: [:0]const u8 = plain; _ = z;}main.zig:3:29: error: expected type '[:0]const u8', found '[]const u8' const z: [:0]const u8 = plain; ^~~~~main.zig:3:29: note: destination pointer requires '0' sentinelEven though plain happens to point at a literal that does end in zero here, the type []const u8 has forgotten that. Types only promise what they say.
C strings: [*:0]const u8
Section titled “C strings: [*:0]const u8”A C string is a pointer to the first character and nothing else: no length. In Zig that’s a many-item pointer with a sentinel, [*:0]const u8. Compared with the plain [*]T from Zig Many-Item Pointers, it’s much more useful, because it knows how it ends. A while loop can find the length:
const std = @import("std");
fn cLength(text: [*:0]const u8) usize { var n: usize = 0; while (text[n] != 0) : (n += 1) {} return n;}
pub fn main() void { std.debug.print("{d}\n", .{cLength("hello")}); std.debug.print("{d}\n", .{cLength("")});}Output:
50That’s what C’s strlen does. You don’t need to write it yourself: std.mem.len counts the bytes, and std.mem.span gives you back a proper slice, which is what you want for the rest of your Zig code:
const std = @import("std");
pub fn main() void { const c_text: [*:0]const u8 = "from C"; std.debug.print("length: {d}\n", .{std.mem.len(c_text)});
const text = std.mem.span(c_text); std.debug.print("{}: {s}\n", .{ @TypeOf(text), text });}Output:
length: 6[:0]const u8: from Cstd.mem.span walks to the zero once and returns a [:0]const u8, a slice with a length that still remembers its zero. From there you can use it like any other string, with {s}, slicing and std.mem functions.
Making a zero-terminated string
Section titled “Making a zero-terminated string”When you have normal text and need a zero-terminated copy, there are three common ways.
Slice a buffer with a sentinel. If you know there’s a 0 at the end position, buf[0..n :0] gives you a [:0] slice. Zig checks that the 0 is really there:
const std = @import("std");
pub fn main() void { var buf = [_]u8{ 'a', 'b', 0, 'c', 'd', 'e' }; buf[5] = 'e'; const ab = buf[0..2 :0]; std.debug.print("{} {s}\n", .{ @TypeOf(ab), ab }); var end: usize = 3; end += 0; const bad = buf[0..end :0]; std.debug.print("{s}\n", .{bad});}You’ll see something like:
*[2:0]u8 abthread 24381 panic: sentinel mismatch: expected 0, found 99main.zig:9:20: 0x11e3f17 in main (main.zig) const bad = buf[0..end :0]; ^buf[2] is 0, so the first slice is fine. buf[3] is 'c' (99), so the second one stops the program instead of handing out a string with no end.
Format into a buffer with std.mem.printSentinel. It works like print, writes into your array, adds the sentinel, and returns the [:0]u8 slice it filled:
const std = @import("std");
pub fn main() !void { var buf: [32]u8 = undefined; const msg = try std.mem.printSentinel(&buf, "user-{d}", .{42}, 0); std.debug.print("{} \"{s}\" len {d}, then {d}\n", .{ @TypeOf(msg), msg, msg.len, msg[msg.len] });}Output:
[:0]u8 "user-42" len 7, then 0Copy with an allocator. allocator.dupeSentinel(u8, text, 0) copies any slice into new memory and adds the zero:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const name: []const u8 = "Ziggy"; const z = try gpa.dupeSentinel(u8, name, 0); defer gpa.free(z); std.debug.print("{} {s}, then {d}\n", .{ @TypeOf(z), z, z[z.len] });}Output:
[:0]u8 Ziggy, then 0init.gpa is the allocator Zig hands to main, and defer gpa.free(z); gives the memory back at the end, as in Zig Defer. Allocators get their own lessons starting with Zig Allocators.
Passing strings to C
Section titled “Passing strings to C”Here’s where all this pays off. A C function that takes a string is declared in Zig with a [*:0]const u8 parameter, so the compiler checks you pass something zero-terminated. This program calls C’s puts directly; it needs the C library, so you run it with -lc:
extern "c" fn puts(text: [*:0]const u8) c_int;
pub fn main() void { _ = puts("Hello from C's puts!"); const name = "Zig"; _ = puts(name);}Run it with zig run main.zig -lc, and you’ll see:
Hello from C's puts!ZigString literals have the zero already, so they fit as they are. A plain []const u8 doesn’t:
extern "c" fn puts(text: [*:0]const u8) c_int;
pub fn main() void { const name: []const u8 = "Zig"; _ = puts(name);}You’ll see:
main.zig:5:14: error: expected type '[*:0]const u8', found '[]const u8' _ = puts(name); ^~~~In C, passing text that isn’t zero-terminated is a classic bug that reads past the end of memory. Here it’s a compile error, and the fix is one of the three ways above, like try gpa.dupeSentinel(u8, name, 0). You’ll do much more of this in Zig C Interop.
Practice
Section titled “Practice”1. Count the words in a C string
Section titled “1. Count the words in a C string”Write countSpaces(text: [*:0]const u8) usize that counts the spaces in a zero-terminated string, without converting it to a slice. Try it on "the quick brown fox".
Hint: loop with an index until text[i] == 0, like cLength in this lesson.
Show solution
const std = @import("std");
fn countSpaces(text: [*:0]const u8) usize { var spaces: usize = 0; var i: usize = 0; while (text[i] != 0) : (i += 1) { if (text[i] == ' ') spaces += 1; } return spaces;}
pub fn main() void { const n = countSpaces("the quick brown fox"); std.debug.print("{d} spaces, so {d} words\n", .{ n, n + 1 });}Output:
3 spaces, so 4 wordsThe zero tells the loop where to stop. Without the sentinel, the function would need a separate length.
2. Back to a slice
Section titled “2. Back to a slice”Take const c_name: [*:0]const u8 = "Ada Lovelace";, turn it into a slice with std.mem.span, and print its first name (everything before the space) and its length.
Hint: once it’s a slice, std.mem.findScalar(u8, name, ' ') returns the index of the space (as an optional, so add .? here because you know there is one).
Show solution
const std = @import("std");
pub fn main() void { const c_name: [*:0]const u8 = "Ada Lovelace"; const name = std.mem.span(c_name); const space = std.mem.findScalar(u8, name, ' ').?; std.debug.print("first name: {s}, full length: {d}\n", .{ name[0..space], name.len });}Output:
first name: Ada, full length: 12After std.mem.span, you have a normal slice and every slice tool works. .? means “I’m sure this optional has a value”; you’ll learn it in Zig Optionals.
- A sentinel is a value stored right after the last item, marking the end. Almost always it’s 0.
[N:0]Tis an array,[:0]Ta slice and[*:0]Ta many-item pointer, each with a 0 after the end..lendoesn’t count the sentinel.- String literals are
*const [N:0]u8, so they work as Zig slices and as C strings. [:0]Tturns into[]Tautomatically; the reverse needs a real zero: slice withbuf[0..n :0], usestd.mem.printSentinel, orallocator.dupeSentinel.std.mem.spanturns a C string into a slice,std.mem.lencounts it.- Declare C string parameters as
[*:0]const u8, and the compiler checks every call.
Next up: Zig Strings in Depth, the std.mem helpers for searching, splitting, trimming and comparing text.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Sentinel-Terminated Arrays:
[N:x]Tand how the sentinel is stored. - Zig language reference: Sentinel-Terminated Slices:
[:x]Tand slicing with a sentinel. - Zig language reference: Sentinel-Terminated Pointers:
[*:0]Tfor C strings. - Zig language reference: String Literals: why literals are zero-terminated.
- Zig 0.17.0 release notes: what changed in the standard library, including the formatting functions.