mirror of
https://github.com/ziglang/zig.git
synced 2024-11-22 20:30:17 +00:00
50 lines
1.3 KiB
Zig
50 lines
1.3 KiB
Zig
const expect = @import("std").testing.expect;
|
|
|
|
test "address of syntax" {
|
|
// Get the address of a variable:
|
|
const x: i32 = 1234;
|
|
const x_ptr = &x;
|
|
|
|
// Dereference a pointer:
|
|
try expect(x_ptr.* == 1234);
|
|
|
|
// When you get the address of a const variable, you get a const single-item pointer.
|
|
try expect(@TypeOf(x_ptr) == *const i32);
|
|
|
|
// If you want to mutate the value, you'd need an address of a mutable variable:
|
|
var y: i32 = 5678;
|
|
const y_ptr = &y;
|
|
try expect(@TypeOf(y_ptr) == *i32);
|
|
y_ptr.* += 1;
|
|
try expect(y_ptr.* == 5679);
|
|
}
|
|
|
|
test "pointer array access" {
|
|
// Taking an address of an individual element gives a
|
|
// single-item pointer. This kind of pointer
|
|
// does not support pointer arithmetic.
|
|
var array = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
|
|
const ptr = &array[2];
|
|
try expect(@TypeOf(ptr) == *u8);
|
|
|
|
try expect(array[2] == 3);
|
|
ptr.* += 1;
|
|
try expect(array[2] == 4);
|
|
}
|
|
|
|
test "slice syntax" {
|
|
// Get a pointer to a variable:
|
|
var x: i32 = 1234;
|
|
const x_ptr = &x;
|
|
|
|
// Convert to array pointer using slice syntax:
|
|
const x_array_ptr = x_ptr[0..1];
|
|
try expect(@TypeOf(x_array_ptr) == *[1]i32);
|
|
|
|
// Coerce to many-item pointer:
|
|
const x_many_ptr: [*]i32 = x_array_ptr;
|
|
try expect(x_many_ptr[0] == 1234);
|
|
}
|
|
|
|
// test
|