Lesson 2 of 85
Lesson Progress: 0%
The & (address-of) operator produces a pointer to a variable. In Zig, you use & to create a pointer from any mutable or immutable variable. The resulting pointer has type *T for mutable variables or *const T for immutable ones. Taking the address does not copy the value; it gives you a reference to the original memory location. This operator is the foundation of all pointer work in Zig.
const std = @import("std");
pub fn main() void {
const x: i32 = 5;
const addr = &x;
_ = addr;
std.debug.print("{d}", .{x});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
&x computes the memory address of the variable x.&x has type *const i32 because x is immutable.const std = @import("std");
pub fn main() void {
const arr = [_]u8{ 1, 2, 3 };
const p = &arr[1];
std.debug.print("{d}", .{p.*});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
*const u8 for a u8.const std = @import("std");
const Point = struct {
x: i32,
y: i32,
};
pub fn main() void {
const pt = Point{ .x = 10, .y = 20 };
const px = &pt.x;
std.debug.print("{d}", .{px.*});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
&arr[1].*i32 because the array and its elements are mutable.arr[1] accesses the element; &arr[1] gets its address.const std = @import("std");
pub fn main() void {
const x: i32 = 100;
const p: *const i32 = &x;
std.debug.print("{any}", .{p == &x});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
&pt.x to get a pointer to a specific struct field.px.* changes pt.x in place.const std = @import("std");
pub fn main() void {
const a: i32 = 1;
const b: i32 = 2;
const pa = &a;
const pb = &b;
std.debug.print("{d}", .{pa.* + pb.*});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
p1 and p2 hold the same address and reference the same memory.p1 is visible when reading through p2.const std = @import("std");
pub fn main() void {
const val: bool = true;
const p = &val;
std.debug.print("{any}", .{p.*});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
*const [N]u8.&msg gives a pointer to the whole string array.p.* gives the entire array.{s} to print the array as a string.Test Incomplete