Basic Pointer Usage in Zig
This Zig program demonstrates the fundamentals of working with pointers in a safe and explicit manner.
const std = @import("std");
pub fn main(_: std.process.Init.Minimal) void {
var x: i32 = 42;
const ptr: *i32 = &x;
std.debug.print("Memory address of x: {}\n", .{ptr});
// Print the original value of x via the pointer
std.debug.print("Value of x via pointer: {}\n", .{ptr.*});
ptr.* = 100;
std.debug.print("Modified value of x via pointer: {}\n", .{x});
}
The program starts by importing the standard library with const std = @import("std"); and defines a minimal main() function that takes std.process.Init.Minimal as a parameter and returns void, indicating no error handling is needed for this simple example.
Inside main(), an integer variable x of type i32 is declared and initialized to 42. A pointer ptr of type *i32 is then created using the address-of operator &x, which points to the memory location of x. The program prints the memory address of x using std.debug.print("Memory address of x: {}\n", .{ptr});, showcasing how Zig can directly output pointer values for debugging purposes.
Next, it dereferences the pointer with ptr.* to access and print the original value of x (42). The code then modifies the value at the pointed location by assigning ptr.* = 100;, which directly updates the original variable x through the pointer. Finally, it prints the modified value of x to confirm the change (now 100).
Save it as ptr.zig and execute it:
$ zig run ptr.zig
Memory address of x: i32@16f17a9b4
Value of x via pointer: 42
Modified value of x via pointer: 100
Happy coding in Zig!