Pointers

Zig has two kinds of pointers:

  • *T - pointer to exactly one item.
    • Supports deref syntax: ptr.*
  • [*]T - 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 @OpaqueType.

These types are closely related to Arrays and Slices:

  • *[N]T - pointer to N items, same as single-item pointer to 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 assert = @import("std").debug.assert;
  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. assert(x_ptr.* == 1234);
  8. // When you get the address of a const variable, you get a const pointer to a single item.
  9. assert(@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. assert(@TypeOf(y_ptr) == *i32);
  14. y_ptr.* += 1;
  15. assert(y_ptr.* == 5679);
  16. }
  17. test "pointer array access" {
  18. // Taking an address of an individual element gives a
  19. // pointer to a single item. 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. assert(@TypeOf(ptr) == *u8);
  24. assert(array[2] == 3);
  25. ptr.* += 1;
  26. assert(array[2] == 4);
  27. }
  1. $ zig test test.zig
  2. 1/2 test "address of syntax"...OK
  3. 2/2 test "pointer array access"...OK
  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 assert = @import("std").debug.assert;
  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. assert(slice.len == 2);
  6. assert(array[3] == 4);
  7. slice[1] += 1;
  8. assert(array[3] == 5);
  9. }
  1. $ zig test test.zig
  2. 1/1 test "pointer slicing"...OK
  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 assert = @import("std").debug.assert;
  2. test "comptime pointers" {
  3. comptime {
  4. var x: i32 = 1;
  5. const ptr = &x;
  6. ptr.* += 1;
  7. x += 1;
  8. assert(ptr.* == 3);
  9. }
  10. }
  1. $ zig test test.zig
  2. 1/1 test "comptime pointers"...OK
  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 assert = @import("std").debug.assert;
  2. test "@ptrToInt and @intToPtr" {
  3. const ptr = @intToPtr(*i32, 0xdeadbee0);
  4. const addr = @ptrToInt(ptr);
  5. assert(@TypeOf(addr) == usize);
  6. assert(addr == 0xdeadbee0);
  7. }
  1. $ zig test test.zig
  2. 1/1 test "@ptrToInt and @intToPtr"...OK
  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 assert = @import("std").debug.assert;
  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. assert(@TypeOf(addr) == usize);
  9. assert(addr == 0xdeadbee0);
  10. }
  11. }
  1. $ zig test test.zig
  2. 1/1 test "comptime @intToPtr"...OK
  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 assert = @import("std").debug.assert;
  2. test "volatile" {
  3. const mmio_ptr = @intToPtr(*volatile u8, 0x12345678);
  4. assert(@TypeOf(mmio_ptr) == *volatile u8);
  5. }
  1. $ zig test test.zig
  2. 1/1 test "volatile"...OK
  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 assert = std.debug.assert;
  3. test "pointer casting" {
  4. const bytes align(@alignOf(u32)) = [_]u8{ 0x12, 0x12, 0x12, 0x12 };
  5. const u32_ptr = @ptrCast(*const u32, &bytes);
  6. assert(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. assert(u32_value == 0x12121212);
  11. // And even another way, the most straightforward way to do it:
  12. assert(@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. assert((*u32).Child == u32);
  17. }
  1. $ zig test test.zig
  2. 1/2 test "pointer casting"...OK
  3. 2/2 test "pointer child type"...OK
  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 assert = std.debug.assert;
  3. test "variable alignment" {
  4. var x: i32 = 1234;
  5. const align_of_i32 = @alignOf(@TypeOf(x));
  6. assert(@TypeOf(&x) == *i32);
  7. assert(*i32 == *align(align_of_i32) i32);
  8. if (std.Target.current.cpu.arch == .x86_64) {
  9. assert((*i32).alignment == 4);
  10. }
  11. }
  1. $ zig test test.zig
  2. 1/1 test "variable alignment"...OK
  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 assert = @import("std").debug.assert;
  2. var foo: u8 align(4) = 100;
  3. test "global variable alignment" {
  4. assert(@TypeOf(&foo).alignment == 4);
  5. assert(@TypeOf(&foo) == *align(4) u8);
  6. const as_pointer_to_array: *[1]u8 = &foo;
  7. const as_slice: []u8 = as_pointer_to_array;
  8. assert(@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. assert(derp() == 1234);
  15. assert(@TypeOf(noop1) == fn() align(1) void);
  16. assert(@TypeOf(noop4) == fn() align(4) void);
  17. noop1();
  18. noop4();
  19. }
  1. $ zig test test.zig
  2. 1/2 test "global variable alignment"...OK
  3. 2/2 test "function alignment"...OK
  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. std.debug.assert(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. 1/1 test "pointer alignment safety"...incorrect alignment
  3. /deps/zig/docgen_tmp/test.zig:10:63: 0x20544b in foo (test)
  4. const int_slice = std.mem.bytesAsSlice(u32, @alignCast(4, slice4));
  5. ^
  6. /deps/zig/docgen_tmp/test.zig:6:25: 0x204bea in test "pointer alignment safety" (test)
  7. std.debug.assert(foo(bytes) == 0x11111111);
  8. ^
  9. /deps/zig/lib/std/special/test_runner.zig:47:28: 0x22bd0e in std.special.main (test)
  10. } else test_fn.func();
  11. ^
  12. /deps/zig/lib/std/start.zig:253:37: 0x2057ad in std.start.posixCallMainAndExit (test)
  13. const result = root.main() catch |err| {
  14. ^
  15. /deps/zig/lib/std/start.zig:123:5: 0x2054ef in std.start._start (test)
  16. @call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
  17. ^
  18. Tests failed. Use the following command to reproduce the failure:
  19. /deps/zig/docgen_tmp/test

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 assert = std.debug.assert;
  3. test "allowzero" {
  4. var zero: usize = 0;
  5. var ptr = @intToPtr(*allowzero i32, zero);
  6. assert(@ptrToInt(ptr) == 0);
  7. }
  1. $ zig test allowzero.zig
  2. 1/1 test "allowzero"...OK
  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: