Knowing where the data is and how much of it there is
C's most famous weakness is the pointer that does not know how long its data is. A function that receives char *name has to trust that the name ends with a zero byte, or that a separate length argument is right. Buffer overflows, the root of decades of security holes, live in that gap between a pointer and its length.
Zig closes the gap with types. An array carries its length in its type. A slice is a pointer and a length, travelling together, and indexing it is bounds-checked in safe builds. A plain pointer to one item cannot be indexed at all, and the rare pointer to an unknown number of items has its own type, so you can see in a signature exactly what a function knows. Strings are not a special type: they are slices of bytes, which keeps the language small and makes UTF-8 handling explicit.
Analogy, not a formal construction
An array is like an egg carton: a fixed number of slots, and the carton's size is printed on the box. A slice is a strip of card you lay over some of the slots, with the first slot and the number of slots written on it; it does not hold any eggs itself. A single-item pointer is a finger pointing at one egg. Moving the carton (copying the array) moves the eggs; moving the card does not.
There is one thing Zig does not have: a growable array built into the language. Lists that grow, like Python's list or C++'s std::vector, are the standard library's std.ArrayList, which needs an allocator and appears in the lesson on allocators.
Definitions
Definition— array
A fixed number of values of one type, stored contiguously: [5]u32. The length is part of the type and known at compile time, [_]u32{ ... } lets the compiler count the elements, and a.len gives the length. Arrays are values: assigning or passing one copies every element.
Definition— single-item pointer
*T points to exactly one T; *const T allows reading but not writing through it. &x takes the address of x, and p.* is the value it points to. Single-item pointers cannot be indexed and have no pointer arithmetic.
Definition— slice
[]T (or []const T) is a pointer to the first of some number of Ts together with that number, s.len. Slicing an array or another slice, a[start..end], makes a slice of the elements from start up to but not including end; a[start..] goes to the end. Indexing and slicing are bounds-checked in safe modes. When both bounds are known at compile time, slicing an array gives a pointer to an array (*[2]u8), which coerces to a slice.
Definition— many-item pointer and sentinel
[*]T points to an unknown number of Ts: it supports indexing and arithmetic but has no length, and is mostly used with C. A sentinel-terminated type such as [:0]u8 or [*:0]const u8 guarantees a marker value (here zero) after the last element, which is how C strings are represented.
Definition— string
By convention, []const u8: a slice of bytes, usually UTF-8 text. A string literal like "São Paulo" has type *const [10:0]u8, a pointer to a constant array of 10 bytes followed by a zero, and coerces to []const u8.
Arrays, pointers and slices in action
const std = @import("std");
pub fn main() void {
// An array's length is part of its type, and arrays are values.
var scores = [_]u32{ 70, 85, 90, 60, 75 }; // type [5]u32
const copy = scores; // copies all five numbers
scores[0] = 100;
std.debug.print("scores[0]={d} copy[0]={d} len={d}\n", .{ scores[0], copy[0], scores.len });
// A single-item pointer refers to one value.
const p: *u32 = &scores[1];
p.* += 1; // .* dereferences
std.debug.print("scores[1]={d}\n", .{scores[1]});
// A slice is a pointer plus a length: a view of part of an array.
const middle: []u32 = scores[1..4]; // elements 1, 2, 3
middle[0] = 0; // writes through to scores
std.debug.print("middle.len={d} scores[1]={d}\n", .{ middle.len, scores[1] });
// Capturing by pointer in a for loop lets the body modify each element.
for (&scores) |*s| s.* = s.* / 10 * 10; // round down to tens
std.debug.print("{any}\n", .{scores});
// ++ joins arrays whose lengths are known at compile time; @splat repeats one value.
const threes: [3]u8 = @splat(3);
const row = [_]u8{ 1, 2 } ++ threes;
std.debug.print("{any}\n", .{row});
// A two-dimensional array.
const grid = [3][3]u8{ .{ 1, 2, 3 }, .{ 4, 5, 6 }, .{ 7, 8, 9 } };
var diagonal: u32 = 0;
for (grid, 0..) |line, i| diagonal += line[i];
std.debug.print("diagonal sum {d}\n", .{diagonal});
}scores[0]=100 copy[0]=70 len=5
scores[1]=86
middle.len=3 scores[1]=0
{ 100, 0, 90, 60, 70 }
{ 1, 2, 3, 3, 3 }
diagonal sum 15const copy = scores;copied the whole array, so changingscores[0]did not affectcopy[0]. If you want to share an array instead, take a pointer or a slice of it.p.* += 1changedscores[1]through a pointer, from 85 to 86. Writing throughmiddle, a slice of elements 1 to 3, then set it to 0: a slice is a view, not a copy.for (&scores) |*s|iterates over a pointer to the array and captures a pointer to each element, so the body can change them. Without the&and the*,swould be a copy of each element.++joins arrays whose lengths are known at compile time, and@splatfills an array with one value; its length comes from the declared type[3]u8. (Older Zig versions had a**operator for repeating arrays; it is gone in 0.17.)
An index past the end of an array is caught in safe builds. A loop written with <= instead of <:
const scores = [_]u32{ 70, 85, 90 };
var i: usize = 0;
while (i <= scores.len) : (i += 1) { // bug: <= goes one too far
std.debug.print("{d}\n", .{scores[i]});
}prints the three scores and then stops with:
thread 2544022 panic: index out of bounds: index 3, len 3
/tmp/tmp0piyqgyz/main.zig:7:42: 0x11ea5fe in main (main.zig)
std.debug.print("{d}\n", .{scores[i]});
^The C version of this loop would read whatever happened to be in memory after the array and carry on.
Strings are bytes
const std = @import("std");
pub fn main() void {
// A string literal is a pointer to a constant, zero-terminated array of bytes.
const city = "São Paulo";
std.debug.print("{s}: type {s}, {d} bytes\n", .{ city, @typeName(@TypeOf(city)), city.len });
// It coerces to []const u8, the type almost all string functions take.
const text: []const u8 = city;
var code_points: usize = 0;
var it = (std.unicode.Utf8View.init(text) catch unreachable).iterator();
while (it.nextCodepoint()) |_| code_points += 1;
std.debug.print("{d} code points\n", .{code_points});
// Strings are compared by content with std.mem.eql, never with ==.
std.debug.print("equal: {}\n", .{std.mem.eql(u8, "kiwi", "kiwi")});
std.debug.print("starts with São: {}\n", .{std.mem.startsWith(u8, text, "São")});
std.debug.print("index of Paulo: {?d}\n", .{std.mem.indexOf(u8, text, "Paulo")});
// Splitting: tokenize skips empty pieces, split keeps them.
const line = " red, green,,blue ";
var tokens = std.mem.tokenizeAny(u8, line, ", ");
while (tokens.next()) |t| std.debug.print("[{s}]", .{t});
std.debug.print("\n", .{});
var parts = std.mem.splitScalar(u8, "a,,b", ',');
while (parts.next()) |p| std.debug.print("<{s}>", .{p});
std.debug.print("\n", .{});
// Building a new string needs memory you provide: here, a buffer on the stack.
var upper_buf: [32]u8 = undefined;
var message_buf: [32]u8 = undefined;
const upper = std.ascii.upperString(&upper_buf, "nairobi");
const message = std.fmt.bufPrint(&message_buf, "{s}!", .{upper}) catch unreachable;
std.debug.print("{s}\n", .{message});
// Multiline string literals start each line with \\ and contain no escapes.
const poem =
\\one line,
\\another line
;
std.debug.print("{s} ({d} bytes)\n", .{ poem, poem.len });
}São Paulo: type *const [10:0]u8, 10 bytes
9 code points
equal: true
starts with São: true
index of Paulo: 5
[red][green][blue]
<a><><b>
NAIROBI!
one line,
another line (22 bytes)"São Paulo" is 10 bytes but 9 characters, because ã takes two bytes in UTF-8. len always counts bytes. When you need characters (strictly, Unicode code points), decode the UTF-8 with std.unicode.Utf8View, as the program does; for user-visible text with accents, emoji and scripts such as Devanagari, even code points are not quite "characters", and serious text processing uses a Unicode library. Character literals follow the same logic: Zig source files are UTF-8, and 'ã' is not a byte but the number of its code point, 227, as a comptime_int; only ASCII characters such as 'a' fit in a u8.
Everything else works on byte slices from std.mem: eql compares contents (using == on two slices is a compile error, because it is unclear whether you mean "same contents" or "same memory"), startsWith, indexOf (which returns ?usize, null if not found, printed with {?d}), and two kinds of splitting. tokenizeAny treats any run of the given delimiter bytes as one separator and skips empty pieces; splitScalar splits at every single delimiter and keeps empty pieces, which is what you want for formats like CSV where an empty field means something.
Creating a new string needs memory. Here it comes from arrays on the stack: upperString writes into upper_buf and returns the part it used, and bufPrint formats into message_buf. The next lessons show how to get memory from an allocator instead, when the size is not known in advance. An earlier draft of this program used one buffer for both steps, so bufPrint read from and wrote to the same bytes. The debug build caught it at once with panic: @memcpy arguments alias, a check that C has no equivalent of.
Functions that take slices
Slices are how Zig functions accept "some number of things". This program sums, reverses, counts and sorts.
const std = @import("std");
fn sum(values: []const i32) i64 {
var total: i64 = 0;
for (values) |v| total += v;
return total;
}
fn reverse(items: []u8) void {
if (items.len < 2) return;
var i: usize = 0;
var j: usize = items.len - 1;
while (i < j) : ({
i += 1;
j -= 1;
}) {
std.mem.swap(u8, &items[i], &items[j]);
}
}
fn countWords(text: []const u8) usize {
var count: usize = 0;
var it = std.mem.tokenizeAny(u8, text, " \t\n");
while (it.next()) |_| count += 1;
return count;
}
pub fn main() void {
const readings = [_]i32{ 12, -3, 7, 30, -1 };
std.debug.print("sum of all {d}, of the last three {d}\n", .{ sum(&readings), sum(readings[2..]) });
var word = "stressed".*; // .* copies the literal into a mutable array
reverse(&word);
std.debug.print("{s}\n", .{&word});
std.debug.print("{d} words\n", .{countWords("the quick brown\tfox\n")});
// Sorting a slice in place.
var data = [_]i32{ 5, -2, 9, 0, 3 };
std.mem.sort(i32, &data, {}, std.sort.asc(i32));
std.debug.print("{any}\n", .{data});
}sum of all 45, of the last three 36
desserts
4 words
{ -2, 0, 3, 5, 9 }sum takes []const i32, promising not to modify the values, and accepts a whole array (&readings coerces to a slice) or any part of one (readings[2..]). reverse takes []u8 because it swaps bytes in place; its while uses a block as the continue expression to step two counters. A string literal is constant, so "stressed".* dereferences it to make a mutable copy of the array in word. std.mem.sort sorts any slice given a comparison; std.sort.asc(i32) provides the ascending one.
Example— const in pointer and slice types
const in a pointer type is about what you may do through the pointer. A *u32 or []u8 allows writing; a *const u32 or []const u8 allows only reading. A mutable pointer coerces to a const one (handing out read-only access is always safe), but never the other way round:
var data = [_]u8{ 1, 2, 3 };
const writable: []u8 = &data;
const readable: []const u8 = writable; // fine: dropping write access
// const again: []u8 = readable; // compile error: would add write accessThis is why a function that only reads should take []const T: it accepts both mutable and constant data, including string literals, which live in read-only memory. @constCast can remove const, but writing through the result to memory that really is constant is illegal behaviour, so treat any @constCast in a code review as a question to answer.
Example— A slice that outlives its array
A slice does not own its data. Returning a slice of a local array is a classic bug:
fn greeting() []const u8 {
var buf: [16]u8 = undefined;
return std.fmt.bufPrint(&buf, "hello {d}", .{42}) catch unreachable;
} // buf's memory is reused after this returns: the slice now danglesThis compiles, and may even appear to work. Zig does not track lifetimes the way Rust does, so it is your job to make sure that whatever a slice points into outlives the slice. The usual fixes are to let the caller supply the buffer (fn greeting(buf: []u8) []const u8) or to allocate the result with an allocator the caller provides and will free. Both patterns appear throughout the standard library.
Who provides the memory?
Every function that produces a string or a list of unknown size has to get memory from somewhere, and Zig code makes that choice visible in the signature. There are three common answers.
The caller provides a buffer. The function writes into a slice it is given and returns the part it used, or an error if the buffer was too small. This needs no heap at all and suits embedded code, hot loops and small, bounded outputs. Here is the pattern with a fixed-buffer writer, which gives you all of print's formatting on top of a plain array:
const std = @import("std");
// The caller provides the buffer; the function returns the part it filled.
fn formatTable(buf: []u8, names: []const []const u8, values: []const u32) ![]const u8 {
var w: std.Io.Writer = .fixed(buf);
for (names, values) |name, value| {
try w.print("{s:<8}|{d:>5}\n", .{ name, value });
}
return w.buffered();
}
pub fn main() !void {
var buf: [256]u8 = undefined;
const table = try formatTable(&buf, &.{ "Lagos", "Lima", "Oslo" }, &.{ 21, 1340, 7 });
std.debug.print("{s}", .{table});
// A buffer that is too small is reported as an error, not overrun.
var tiny: [10]u8 = undefined;
if (formatTable(&tiny, &.{"Lagos"}, &.{21})) |_| {
std.debug.print("fits\n", .{});
} else |err| {
std.debug.print("tiny buffer: {t}\n", .{err});
}
// A zero-terminated string, as C code would hand it to you.
const c_string: [*:0]const u8 = " padded text \n";
const as_slice: []const u8 = std.mem.span(c_string); // finds the zero, gives a slice
const trimmed = std.mem.trim(u8, as_slice, " \n");
std.debug.print("[{s}] {d} -> {d} bytes\n", .{ trimmed, as_slice.len, trimmed.len });
}Lagos | 21
Lima | 1340
Oslo | 7
tiny buffer: WriteFailed
[padded text] 15 -> 11 bytesstd.Io.Writer.fixed(buf) creates a writer whose whole buffer is buf; when it fills up, writing fails with error.WriteFailed instead of overrunning anything, and buffered() returns what was written. The for (names, values) loop walks two slices in step; in safe builds it checks that they have the same length. The last lines show the bridge from C: a [*:0]const u8 knows only where its bytes start, std.mem.span walks to the zero terminator and returns an ordinary slice, and std.mem.trim returns a narrower view of the same bytes without copying.
The caller provides an allocator. The function allocates exactly the memory it needs and returns it, and the caller must free it. std.fmt.allocPrint(allocator, ...) is the allocator version of bufPrint. This is the subject of the allocators lesson.
The result points into the input. trim, tokenizeAny and indexOf return slices or positions inside the slice you gave them, so they need no memory at all, but their results are only valid as long as the input is.
Reading a Zig function signature, you can always tell which of these it does, which is exactly the point of "no hidden allocations".
Common misconceptions
Misconception
"Passing an array to a function passes a reference, as in C." In Zig an array parameter is copied like any other value. Pass a slice ([]T or []const T) or a pointer when you want the function to see or change the caller's elements.
Misconception
"str.len is the number of characters." It is the number of bytes. For ASCII text the two are the same, which is why the bug hides until someone types é, ß or 東京.
Misconception
"A string literal is a mutable buffer." Literals are stored in read-only memory and have const types, so you cannot write through them. To get a mutable copy, dereference the literal into an array (var word = "stressed".*;) or copy it into a buffer you own.
Misconception
"I can compare strings with ==." == is not defined for slices. Use std.mem.eql(u8, a, b) for equal contents, or compare a.ptr and a.len if you really mean "the same memory".
Misconception
"Slices are bounds-checked, so out-of-bounds access is impossible." Checks are inserted in debug and safe modes only. In fast and small modes they are removed, and an out-of-bounds index is undefined behaviour, exactly as in C. Test in a safe mode, and ship in one where you can afford it.
Exercises
1. Arrays, slices, pointers and strings
CoreComputationalWhat does this program print?
const std = @import("std");
pub fn main() void {
var a = [_]u8{ 1, 2, 3, 4 };
const b = a;
const s = a[1..3];
s[0] = 9;
a[2] = 7;
std.debug.print("{d} {d} {d} {d}\n", .{ a[1], b[1], s[1], s.len });
}
2. Arrays, slices, pointers and strings
Warm-upComputationalWhat does std.debug.print("{d}\n", .{"naïve".len}); print? (The source file is UTF-8, as all Zig source is.)
3. Arrays, slices, pointers and strings
CoreComputationalWhat does this program print?
var it = std.mem.splitScalar(u8, ",x,,y,", ',');
var n: usize = 0;
while (it.next()) |_| n += 1;
var tok = std.mem.tokenizeScalar(u8, ",x,,y,", ',');
var m: usize = 0;
while (tok.next()) |_| m += 1;
std.debug.print("{d} {d}\n", .{ n, m });
4. Arrays, slices, pointers and strings
CoreComputationalWhat does this program print?
const std = @import("std");
fn bump(xs: []u32) void {
for (xs) |*x| x.* += 1;
}
fn bumpCopy(xs: [3]u32) void {
var local = xs;
for (&local) |*x| x.* += 100;
}
pub fn main() void {
var data = [_]u32{ 1, 2, 3 };
bump(data[1..]);
bumpCopy(data);
std.debug.print("{any}\n", .{data});
}
5. Arrays, slices, pointers and strings
CoreHumanA function must read some number of temperature readings that the caller already has in memory, and must not change them. Which parameter type fits best?
6. Arrays, slices, pointers and strings
StretchHumanWhich of these functions return a slice that is safe to use after the function returns? Select all that apply.
Further reading and resources
- Zig language reference: Arrays, Pointers and Slices
- Zig language reference: String Literals and Unicode Code Point Literals
- std.mem (in the standard library documentation)eql, indexOf, startsWith, splitScalar, tokenizeAny, sort and many more functions on slices.