Pointers are objects that store a memory address. |
|
const std = @import("std"); const print = std.debug.print; |
|
Single-item pointers point to exactly one value. |
const Single = *bool; |
Many-item pointers point to an unknown number of values. Unless you’re interfacing with C code, you probably won’t use these types of pointers, so we’ll skip over them. |
const Many = [*]bool; |
All pointers in Zig point to a non- |
const Null = ?*bool; |
pub fn main() !void { |
|
To create a single-item pointer, use the |
var v = false; const ptr: *bool = &v; print("pointer: {}\n", .{ptr}); |
To access the value located at the memory address stored by a
single-item pointer, use the |
ptr.* = true; print("value: {}\n", .{ptr.*}); |
If a pointer is |
const const_ptr: *bool = &v; const_ptr.* = false; |
If a pointee is |
const cf = false; const ct = true; var ptr_to_const: *const bool = &cf; ptr_to_const = &ct; } |
$ zig run pointers.zig pointer: bool@7ff7b26e24a7 value: true |
Next example: Slices.