Pointers

Zig has two kinds of pointers: single-item and many-item.

  • *T - single-item pointer to exactly one item.
    • Supports deref syntax: ptr.*
  • [*]T - many-item pointer to unknown number of items.
    • Supports index syntax: ptr[i]
    • Supports slice syntax: ptr[start..end]
    • Supports pointer arithmetic: ptr + x, ptr - x
    • T must have a known size, which means that it cannot be c_void or any other opaque type.

These types are closely related to Arrays and Slices:

  • *[N]T - pointer to N items, same as single-item pointer to an array.

    • Supports index syntax: array_ptr[i]
    • Supports slice syntax: array_ptr[start..end]
    • Supports len property: array_ptr.len
  • []T - pointer to runtime-known number of items.

    • Supports index syntax: slice[i]
    • Supports slice syntax: slice[start..end]
    • Supports len property: slice.len

Use &x to obtain a single-item pointer:

test.zig

  1. const expect = @import("std").testing.expect;
  2. test "address of syntax" {
  3. // Get the address of a variable:
  4. const x: i32 = 1234;
  5. const x_ptr = &x;
  6. // Dereference a pointer:
  7. try expect(x_ptr.* == 1234);
  8. // When you get the address of a const variable, you get a const single-item pointer.
  9. try expect(@TypeOf(x_ptr) == *const i32);
  10. // If you want to mutate the value, you'd need an address of a mutable variable:
  11. var y: i32 = 5678;
  12. const y_ptr = &y;
  13. try expect(@TypeOf(y_ptr) == *i32);
  14. y_ptr.* += 1;
  15. try expect(y_ptr.* == 5679);
  16. }
  17. test "pointer array access" {
  18. // Taking an address of an individual element gives a
  19. // single-item pointer. This kind of pointer
  20. // does not support pointer arithmetic.
  21. var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  22. const ptr = &array[2];
  23. try expect(@TypeOf(ptr) == *u8);
  24. try expect(array[2] == 3);
  25. ptr.* += 1;
  26. try expect(array[2] == 4);
  27. }
  1. $ zig test test.zig
  2. Test [1/2] test "address of syntax"...
  3. Test [2/2] test "pointer array access"...
  4. All 2 tests passed.

In Zig, we generally prefer Slices rather than Sentinel-Terminated Pointers. You can turn an array or pointer into a slice using slice syntax.

Slices have bounds checking and are therefore protected against this kind of undefined behavior. This is one reason we prefer slices to pointers.

test.zig

  1. const expect = @import("std").testing.expect;
  2. test "pointer slicing" {
  3. var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  4. const slice = array[2..4];
  5. try expect(slice.len == 2);
  6. try expect(array[3] == 4);
  7. slice[1] += 1;
  8. try expect(array[3] == 5);
  9. }
  1. $ zig test test.zig
  2. Test [1/1] test "pointer slicing"...
  3. All 1 tests passed.

Pointers work at compile-time too, as long as the code does not depend on an undefined memory layout:

test.zig

  1. const expect = @import("std").testing.expect;
  2. test "comptime pointers" {
  3. comptime {
  4. var x: i32 = 1;
  5. const ptr = &x;
  6. ptr.* += 1;
  7. x += 1;
  8. try expect(ptr.* == 3);
  9. }
  10. }
  1. $ zig test test.zig
  2. Test [1/1] test "comptime pointers"...
  3. All 1 tests passed.

To convert an integer address into a pointer, use @intToPtr. To convert a pointer to an integer, use @ptrToInt:

test.zig

  1. const expect = @import("std").testing.expect;
  2. test "@ptrToInt and @intToPtr" {
  3. const ptr = @intToPtr(*i32, 0xdeadbee0);
  4. const addr = @ptrToInt(ptr);
  5. try expect(@TypeOf(addr) == usize);
  6. try expect(addr == 0xdeadbee0);
  7. }
  1. $ zig test test.zig
  2. Test [1/1] test "@ptrToInt and @intToPtr"...
  3. All 1 tests passed.

Zig is able to preserve memory addresses in comptime code, as long as the pointer is never dereferenced:

test.zig

  1. const expect = @import("std").testing.expect;
  2. test "comptime @intToPtr" {
  3. comptime {
  4. // Zig is able to do this at compile-time, as long as
  5. // ptr is never dereferenced.
  6. const ptr = @intToPtr(*i32, 0xdeadbee0);
  7. const addr = @ptrToInt(ptr);
  8. try expect(@TypeOf(addr) == usize);
  9. try expect(addr == 0xdeadbee0);
  10. }
  11. }
  1. $ zig test test.zig
  2. Test [1/1] test "comptime @intToPtr"...
  3. All 1 tests passed.

See also:

volatile

Loads and stores are assumed to not have side effects. If a given load or store should have side effects, such as Memory Mapped Input/Output (MMIO), use volatile. In the following code, loads and stores with mmio_ptr are guaranteed to all happen and in the same order as in source code:

test.zig

  1. const expect = @import("std").testing.expect;
  2. test "volatile" {
  3. const mmio_ptr = @intToPtr(*volatile u8, 0x12345678);
  4. try expect(@TypeOf(mmio_ptr) == *volatile u8);
  5. }
  1. $ zig test test.zig
  2. Test [1/1] test "volatile"...
  3. All 1 tests passed.

Note that volatile is unrelated to concurrency and Atomics. If you see code that is using volatile for something other than Memory Mapped Input/Output, it is probably a bug.

To convert one pointer type to another, use @ptrCast. This is an unsafe operation that Zig cannot protect you against. Use @ptrCast only when other conversions are not possible.

test.zig

  1. const std = @import("std");
  2. const expect = std.testing.expect;
  3. test "pointer casting" {
  4. const bytes align(@alignOf(u32)) = [_]u8{ 0x12, 0x12, 0x12, 0x12 };
  5. const u32_ptr = @ptrCast(*const u32, &bytes);
  6. try expect(u32_ptr.* == 0x12121212);
  7. // Even this example is contrived - there are better ways to do the above than
  8. // pointer casting. For example, using a slice narrowing cast:
  9. const u32_value = std.mem.bytesAsSlice(u32, bytes[0..])[0];
  10. try expect(u32_value == 0x12121212);
  11. // And even another way, the most straightforward way to do it:
  12. try expect(@bitCast(u32, bytes) == 0x12121212);
  13. }
  14. test "pointer child type" {
  15. // pointer types have a `child` field which tells you the type they point to.
  16. try expect(@typeInfo(*u32).Pointer.child == u32);
  17. }
  1. $ zig test test.zig
  2. Test [1/2] test "pointer casting"...
  3. Test [2/2] test "pointer child type"...
  4. All 2 tests passed.

Alignment

Each type has an alignment - a number of bytes such that, when a value of the type is loaded from or stored to memory, the memory address must be evenly divisible by this number. You can use @alignOf to find out this value for any type.

Alignment depends on the CPU architecture, but is always a power of two, and less than 1 << 29.

In Zig, a pointer type has an alignment value. If the value is equal to the alignment of the underlying type, it can be omitted from the type:

test.zig

  1. const std = @import("std");
  2. const expect = std.testing.expect;
  3. test "variable alignment" {
  4. var x: i32 = 1234;
  5. const align_of_i32 = @alignOf(@TypeOf(x));
  6. try expect(@TypeOf(&x) == *i32);
  7. try expect(*i32 == *align(align_of_i32) i32);
  8. if (std.Target.current.cpu.arch == .x86_64) {
  9. try expect(@typeInfo(*i32).Pointer.alignment == 4);
  10. }
  11. }
  1. $ zig test test.zig
  2. Test [1/1] test "variable alignment"...
  3. All 1 tests passed.

In the same way that a *i32 can be coerced to a *const i32, a pointer with a larger alignment can be implicitly cast to a pointer with a smaller alignment, but not vice versa.

You can specify alignment on variables and functions. If you do this, then pointers to them get the specified alignment:

test.zig

  1. const expect = @import("std").testing.expect;
  2. var foo: u8 align(4) = 100;
  3. test "global variable alignment" {
  4. try expect(@typeInfo(@TypeOf(&foo)).Pointer.alignment == 4);
  5. try expect(@TypeOf(&foo) == *align(4) u8);
  6. const as_pointer_to_array: *[1]u8 = &foo;
  7. const as_slice: []u8 = as_pointer_to_array;
  8. try expect(@TypeOf(as_slice) == []align(4) u8);
  9. }
  10. fn derp() align(@sizeOf(usize) * 2) i32 { return 1234; }
  11. fn noop1() align(1) void {}
  12. fn noop4() align(4) void {}
  13. test "function alignment" {
  14. try expect(derp() == 1234);
  15. try expect(@TypeOf(noop1) == fn() align(1) void);
  16. try expect(@TypeOf(noop4) == fn() align(4) void);
  17. noop1();
  18. noop4();
  19. }
  1. $ zig test test.zig
  2. Test [1/2] test "global variable alignment"...
  3. Test [2/2] test "function alignment"...
  4. All 2 tests passed.

If you have a pointer or a slice that has a small alignment, but you know that it actually has a bigger alignment, use @alignCast to change the pointer into a more aligned pointer. This is a no-op at runtime, but inserts a safety check:

test.zig

  1. const std = @import("std");
  2. test "pointer alignment safety" {
  3. var array align(4) = [_]u32{ 0x11111111, 0x11111111 };
  4. const bytes = std.mem.sliceAsBytes(array[0..]);
  5. try std.testing.expect(foo(bytes) == 0x11111111);
  6. }
  7. fn foo(bytes: []u8) u32 {
  8. const slice4 = bytes[1..5];
  9. const int_slice = std.mem.bytesAsSlice(u32, @alignCast(4, slice4));
  10. return int_slice[0];
  11. }
  1. $ zig test test.zig
  2. Test [1/1] test "pointer alignment safety"...
  3. thread 10521 panic: incorrect alignment
  4. /home/andy/Downloads/zig/docgen_tmp/test.zig:10:63: 0x2081bc in foo (test)
  5. const int_slice = std.mem.bytesAsSlice(u32, @alignCast(4, slice4));
  6. ^
  7. /home/andy/Downloads/zig/docgen_tmp/test.zig:6:31: 0x206799 in test "pointer alignment safety" (test)
  8. try std.testing.expect(foo(bytes) == 0x11111111);
  9. ^
  10. /home/andy/Downloads/zig/lib/std/special/test_runner.zig:76:28: 0x22d2da in std.special.main (test)
  11. } else test_fn.func();
  12. ^
  13. /home/andy/Downloads/zig/lib/std/start.zig:471:37: 0x22583a in std.start.callMain (test)
  14. const result = root.main() catch |err| {
  15. ^
  16. /home/andy/Downloads/zig/lib/std/start.zig:413:12: 0x20970e in std.start.callMainWithArgs (test)
  17. return @call(.{ .modifier = .always_inline }, callMain, .{});
  18. ^
  19. /home/andy/Downloads/zig/lib/std/start.zig:332:17: 0x2086a6 in std.start.posixCallMainAndExit (test)
  20. std.os.exit(@call(.{ .modifier = .always_inline }, callMainWithArgs, .{ argc, argv, envp }));
  21. ^
  22. /home/andy/Downloads/zig/lib/std/start.zig:245:5: 0x2084b2 in std.start._start (test)
  23. @call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
  24. ^
  25. error: the following test command crashed:
  26. docgen_tmp/zig-cache/o/333a8741816702dafd0ff99af380ebb1/test /home/andy/Downloads/zig/build-release/zig

allowzero

This pointer attribute allows a pointer to have address zero. This is only ever needed on the freestanding OS target, where the address zero is mappable. If you want to represent null pointers, use Optional Pointers instead. Optional Pointers with allowzero are not the same size as pointers. In this code example, if the pointer did not have the allowzero attribute, this would be a Pointer Cast Invalid Null panic:

allowzero.zig

  1. const std = @import("std");
  2. const expect = std.testing.expect;
  3. test "allowzero" {
  4. var zero: usize = 0;
  5. var ptr = @intToPtr(*allowzero i32, zero);
  6. try expect(@ptrToInt(ptr) == 0);
  7. }
  1. $ zig test allowzero.zig
  2. Test [1/1] test "allowzero"...
  3. All 1 tests passed.

Sentinel-Terminated Pointers

The syntax [*:x]T describes a pointer that has a length determined by a sentinel value. This provides protection against buffer overflow and overreads.

test.zig

  1. const std = @import("std");
  2. // This is also available as `std.c.printf`.
  3. pub extern "c" fn printf(format: [*:0]const u8, ...) c_int;
  4. pub fn main() anyerror!void {
  5. _ = printf("Hello, world!\n"); // OK
  6. const msg = "Hello, world!\n";
  7. const non_null_terminated_msg: [msg.len]u8 = msg.*;
  8. _ = printf(&non_null_terminated_msg);
  9. }
  1. $ zig build-exe test.zig -lc
  2. ./docgen_tmp/test.zig:11:17: error: expected type '[*:0]const u8', found '*const [14]u8'
  3. _ = printf(&non_null_terminated_msg);
  4. ^
  5. ./docgen_tmp/test.zig:11:17: note: destination pointer requires a terminating '0' sentinel
  6. _ = printf(&non_null_terminated_msg);
  7. ^

See also: