Lesson 3 of 85
Lesson Progress: 0%
Dereferencing a pointer means accessing the value stored at the memory address the pointer holds. In Zig, you use the .* operator to dereference a pointer. If you have a pointer p of type *T, then p.* gives you the value of type T. Dereferencing a mutable pointer allows you to read or write the underlying value. Zig ensures that dereferencing is safe by never allowing null pointers in safe code.
const std = @import("std");
pub fn main() void {
const x: i32 = 10;
const p: *const i32 = &x;
std.debug.print("{d}", .{p.*});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
p.* reads the value that the pointer p points to.p.* is the pointed-to type, i32 in this case.*const T gives a read-only view of the value.p.* anywhere you would use the value directly.const std = @import("std");
pub fn main() void {
var y: i32 = 5;
const p: *i32 = &y;
p.* = 20;
std.debug.print("{d}", .{y});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
*T, you can assign to p.*.p.* = p.* + 3 reads the current value, adds 3, and writes it back.val.*T not *const T).const std = @import("std");
const Point = struct {
x: i32,
y: i32,
};
pub fn main() void {
const pt = Point{ .x = 3, .y = 7 };
const p: *const Point = &pt;
std.debug.print("{d}", .{p.*.x + p.*.y});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
p.*.field to access fields.p.*.x = 10 modifies the field through the dereferenced pointer.*Point.const std = @import("std");
pub fn main() void {
const val: f64 = 2.5;
const p: *const f64 = &val;
std.debug.print("{d}", .{p.*});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
pa.* == pb.* to compare the values behind two pointers.{any} format specifier.const std = @import("std");
pub fn main() void {
var x: u8 = 0;
const p: *u8 = &x;
p.* = 255;
std.debug.print("{d}", .{x});
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
*const *const T, dereference twice to reach the value.pp.* gives the inner pointer p.pp.*.* gives the original value x..* removes one level of indirection.const std = @import("std");
pub fn main() void {
const a: i32 = 4;
const b: i32 = 3;
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:
p.*.a and p.*.b.Test Incomplete