In Zig, a single-item pointer holds the address of one item. The item can be a scalar such as an i32 or an entire array. Write the type as *T: for example, *i32 means a single-item pointer to an i32. section 2.2.1 section 2.2.2
Use & to take a value’s address and .* to dereference the pointer. If x is mutable, `const x_ptr: *i32 = &x` lets you write `x_ptr.* = 456`; the change is visible through x too. The pointer binding is constant, but the item it points to is mutable. section 2.2.1
Listing 2.6 Single-item pointers
const std = @import("std");
pub fn main() void {
var x: i32 = 123; #1
std.debug.print("{}\n", .{x});
const x_ptr: *i32 = &x; #2
x_ptr.* = 456; #3
std.debug.print("{}\n", .{x_ptr.*}); #4
std.debug.print("{}\n", .{x});
}
Run the listing to see a write through x_ptr change x from 123 to 456. section 2.2.1
A pointer to constant data cannot be used to write that data. For example, taking the address of a const i32 yields a pointer through which assignment fails at compile time. A mutable pointer can also be coerced to a constant pointer, as in `const p: *const i32 = mutable_ptr`. section 2.2.1
Listing 2.7 Pointer mutability
const std = @import("std");
pub fn main() void {
var a: i32 = 123;
const b: i32 = 456; #1
const a_ptr = &a; #2
const b_ptr = &b; #3
a_ptr.* = 25; #4
b_ptr.* = 50; #5
a = b_ptr.*; #6
std.debug.print("a = {}, b = {}\n", .{a, b});
}
Compare a pointer to a var with a pointer to a const; the attempted write through the latter triggers a compiler error. section 2.2.1
A pointer to an array has the form *[N]T; use *const [N]T to prevent mutation through it. This lets a function work with an array without receiving a copy. The length N is still part of the type, though, so a slice is the alternative when the length must be known at runtime. section 2.2.2
A string literal is a pointer to one array
`@TypeOf("I am a string literal")` produces `*const [21:0]u8`: a constant single-item pointer to an array of 21 bytes with a zero terminator. The pointer avoids copying the read-only bytes, can be dereferenced to obtain the array, and can coerce to []const u8. The terminator also allows direct passage to C functions. section 2.2.5
