Skip to content

Zig Arrays

An array is a fixed number of values of the same type, stored one after another in memory: five scores, seven day names, a 3 × 3 game board. In Zig, the length is part of the array’s type and is decided while compiling, so an array never grows or shrinks. That sounds limiting, but it makes arrays fast, simple and safe, and they’re the base that slices (the type you’ll pass around most) are built on.

You write an array type as [N]T: N items of type T. Put the values in braces after it:

const std = @import("std");
pub fn main() void {
var scores = [5]u32{ 70, 85, 92, 60, 77 };
std.debug.print("first: {d}, last: {d}\n", .{ scores[0], scores[4] });
scores[3] = 65;
std.debug.print("all: {any}\n", .{scores});
std.debug.print("length: {d}\n", .{scores.len});
}

Output:

first: 70, last: 77
all: { 70, 85, 92, 65, 77 }
length: 5
  • [5]u32{ ... } makes an array of five u32 values.
  • scores[0] is the first item. Like in C, Python and JavaScript, counting starts at 0, so the last of five items is scores[4].
  • scores[3] = 65; changes one item. That needs a var; the items of a const array can’t change.
  • .len is the number of items. {any} prints the whole array.

Counting the items yourself is boring and easy to get wrong. Write _ instead of the number, and Zig counts them for you:

const std = @import("std");
pub fn main() void {
const primes = [_]u8{ 2, 3, 5, 7, 11 };
std.debug.print("{} with {d} items\n", .{ @TypeOf(primes), primes.len });
}

Output:

[5]u8 with 5 items

The type is still [5]u8; _ just means “count them”. This is the form you’ll write most. If you do give a number, it has to match: [3]u8{ 1, 2 } fails with expected 3 array elements; found 2.

If Zig can see while compiling that an index is too big, it stops the build:

pub fn main() void {
const a = [3]u8{ 1, 2, 3 };
_ = a[3];
}
main.zig:3:11: error: index 3 outside array of length 3
_ = a[3];
^

When the index is only known while running, Zig checks it then. Here’s the classic off-by-one mistake, using <= instead of <:

const std = @import("std");
pub fn main() void {
const days = [_][]const u8{ "Mon", "Tue", "Wed" };
var i: usize = 0;
while (i <= days.len) : (i += 1) {
std.debug.print("{s}\n", .{days[i]});
}
}

You’ll see something like:

Mon
Tue
Wed
thread 22200 panic: index out of bounds: index 3, len 3
main.zig:7:40: 0x11e3e16 in main (main.zig)
std.debug.print("{s}\n", .{days[i]});
^

In C this would quietly read whatever memory comes after the array. Zig stops the program and tells you the index, the length and the line. These checks are on in debug and safe builds; in fast and small builds they’re left out for speed, so test in debug mode. [_][]const u8 here is an array of strings, by the way: each item is a []const u8.

You already know for from Zig For. It works directly on arrays, and you can count along with 0.. (or 1.. to start at 1):

const std = @import("std");
pub fn main() void {
const weekdays = [_][]const u8{ "Mon", "Tue", "Wed", "Thu", "Fri" };
const weekend = [_][]const u8{ "Sat", "Sun" };
const week = weekdays ++ weekend;
std.debug.print("{d} days\n", .{week.len});
for (week, 1..) |day, n| {
std.debug.print("{d}. {s}\n", .{ n, day });
}
}

Output:

7 days
1. Mon
2. Tue
3. Wed
4. Thu
5. Fri
6. Sat
7. Sun

++ joined the two arrays into one array of 7 items; more on that below. To change the items in a loop, loop over &array and capture a pointer with |*item|, as you’ll see in the next section.

To make an array where every item has the same value, use @splat. To fill it in a loop instead, start with undefined (meaning “no value yet”) and set every item before you read it:

const std = @import("std");
pub fn main() void {
var zeros: [5]u8 = @splat(0);
const sevens: [3]i32 = @splat(7);
zeros[1] = 4;
std.debug.print("{any}\n{any}\n", .{ zeros, sevens });
var squares: [6]u32 = undefined;
for (&squares, 0..) |*sq, i| {
sq.* = @intCast(i * i);
}
std.debug.print("{any}\n", .{squares});
}

Output:

{ 0, 4, 0, 0, 0 }
{ 7, 7, 7 }
{ 0, 1, 4, 9, 16, 25 }

@splat(0) copies one value into every slot. It needs to know the array type, so write the type on the variable: var zeros: [5]u8 = @splat(0);. In the loop, &squares and |*sq| give you a pointer to each item, and sq.* = ... writes through it (pointers come in Zig Pointers). @intCast turns the usize index into a u32.

++ puts two arrays end to end and gives you a new, longer array. Both lengths have to be known while compiling, which is always true for arrays, so the values themselves can come from anywhere:

const std = @import("std");
pub fn main() void {
var first = [_]u8{ 1, 2, 3 };
first[0] = 10;
const both = first ++ [_]u8{ 4, 5 };
std.debug.print("{any}\n", .{both});
}

Output:

{ 10, 2, 3, 4, 5 }

The result has the type [5]u8, worked out while compiling. What ++ can’t do is join two things whose length is only known while running, like a slice of text the user typed. For that you need a buffer or an allocator; you saw std.mem.print for text in Zig Strings.

Since the length is part of the type, you can’t make an array from a length that’s only known at run time:

const std = @import("std");
pub fn main() void {
var n: usize = 5;
n += 1;
var buf: [n]u8 = undefined;
_ = &buf;
}
main.zig:6:15: error: unable to resolve comptime value
var buf: [n]u8 = undefined;
^
main.zig:6:15: note: types must be comptime-known

When you don’t know the size in advance, you have two choices: make an array big enough for the worst case and use part of it (with a slice), or ask an allocator for memory, or use an ArrayList, which grows as needed.

This surprises people coming from JavaScript, Python or Java: in Zig, an array is a value, like a number. Assigning it to another variable copies all the items:

const std = @import("std");
pub fn main() void {
const a = [_]u8{ 1, 2, 3 };
var b = a;
b[0] = 99;
std.debug.print("a: {any}\nb: {any}\n", .{ a, b });
std.debug.print("equal: {}\n", .{std.mem.eql(u8, &a, &b)});
const c = [_]u8{ 1, 2, 3 };
std.debug.print("a == c: {}\n", .{std.mem.eql(u8, &a, &c)});
}

Output:

a: { 1, 2, 3 }
b: { 99, 2, 3 }
equal: false
a == c: true

Changing b didn’t touch a. The same goes for passing an array to a function: the function gets a copy, as you saw in Zig Function Parameters. To compare two arrays, use std.mem.eql with & in front of each. == doesn’t work on arrays: you get operator == not allowed for type '[3]u8'.

An array’s items can be arrays too. [3][4]u8 is “3 rows, each an array of 4 u8”:

const std = @import("std");
pub fn main() void {
var grid = [3][4]u8{
.{ 1, 2, 3, 4 },
.{ 5, 6, 7, 8 },
.{ 9, 10, 11, 12 },
};
grid[1][2] = 0;
for (grid) |row| {
for (row) |cell| {
std.debug.print("{d:>3}", .{cell});
}
std.debug.print("\n", .{});
}
std.debug.print("rows: {d}, columns: {d}\n", .{ grid.len, grid[0].len });
}

Output:

1 2 3 4
5 6 0 8
9 10 11 12
rows: 3, columns: 4

grid[1][2] is row 1, column 2 (both counting from 0). Inside the outer braces, each row is written .{ ... }: Zig already knows each row is a [4]u8, so you don’t have to repeat the type. {d:>3} prints each number right-aligned in 3 spaces, so the columns line up. The reference on multidimensional arrays has more.

When an array holds a few values with different meanings, you can unpack it into separate names in one line:

const std = @import("std");
pub fn main() void {
const rgb = [_]u8{ 255, 128, 0 };
const red, const green, const blue = rgb;
std.debug.print("r={d} g={d} b={d}\n", .{ red, green, blue });
}

Output:

r=255 g=128 b=0

The number of names must match the array’s length. It’s the same syntax you used to unpack a tuple in Zig Functions.

Make an array of seven daily temperatures (i32) and print their sum and their average.

Hint: add them up in a for loop. To divide, @divTrunc(sum, @as(i32, temps.len)) works because temps.len is known while compiling.

Show solution
const std = @import("std");
pub fn main() void {
const temps = [_]i32{ 12, 15, 9, 20, 18, 11, 13 };
var sum: i32 = 0;
for (temps) |t| sum += t;
const avg = @divTrunc(sum, @as(i32, temps.len));
std.debug.print("sum: {d}, average: {d}\n", .{ sum, avg });
}

Output:

sum: 98, average: 14

@divTrunc is division that drops the remainder; Zig makes you pick a rounding style when dividing signed numbers. @as(i32, temps.len) works without a cast because 7 fits in an i32 and Zig knows it at compile time.

Given const word = [_]u8{ 'z', 'i', 'g', 'g', 'y' };, build a second array with the letters in reverse order and print both with {s}.

Hint: make var reversed: [word.len]u8 = undefined; and loop over word with an index. Item i goes to position word.len - 1 - i.

Show solution
const std = @import("std");
pub fn main() void {
const word = [_]u8{ 'z', 'i', 'g', 'g', 'y' };
var reversed: [word.len]u8 = undefined;
for (word, 0..) |letter, i| {
reversed[word.len - 1 - i] = letter;
}
std.debug.print("{s} -> {s}\n", .{ word, reversed });
}

Output:

ziggy -> yggiz

[word.len]u8 is allowed because word.len is known while compiling. An array of u8 can be printed as text with {s}.

Make a 3 × 3 board of u8, filled with '.'. Put an 'X' in the middle and an 'O' in the top-right corner, then print the board, one row per line.

Hint: var board: [3][3]u8 = @splat(@splat('.')); fills every row. Each row is a [3]u8, so you can print it with {s}.

Show solution
const std = @import("std");
pub fn main() void {
var board: [3][3]u8 = @splat(@splat('.'));
board[1][1] = 'X';
board[0][2] = 'O';
for (board) |row| {
std.debug.print("{s}\n", .{row});
}
}

Output:

..O
.X.
...

The inner @splat('.') makes one row, and the outer @splat copies that row three times.

  • An array type is [N]T: exactly N items of type T. Write [_]T{ ... } to let Zig count.
  • Items are numbered from 0; .len is the length. Bad indexes are caught while compiling when possible, otherwise with a panic in safe builds.
  • Fill an array with @splat(value). The old ** operator was removed in Zig 0.17.
  • ++ joins arrays into a new, longer array.
  • The length must be known while compiling. For sizes you only know at run time, use slices, allocators or an ArrayList.
  • Arrays are values: assigning copies them. Compare them with std.mem.eql, not ==.
  • [rows][cols]T makes a grid; grid[r][c] picks one cell.

Next up: Zig Pointers, how to point at a value instead of copying it, with *T, &x and ptr.*.

Quick check

1. What is the type of [_]u8{ 1, 2, 3, 4 }?
2. After var b = a; b[0] = 9; with a an array, what happened to a[0]?
3. How do you make an array of 10 zeros in Zig 0.17?
4. Can you write var buf: [n]u8 = undefined; where n is read from the user?