mirror of
https://github.com/ziglang/zig.git
synced 2024-11-26 23:22:44 +00:00
36 lines
1014 B
Zig
36 lines
1014 B
Zig
const expect = @import("std").testing.expect;
|
|
|
|
test "pointer arithmetic with many-item pointer" {
|
|
const array = [_]i32{ 1, 2, 3, 4 };
|
|
var ptr: [*]const i32 = &array;
|
|
|
|
try expect(ptr[0] == 1);
|
|
ptr += 1;
|
|
try expect(ptr[0] == 2);
|
|
|
|
// slicing a many-item pointer without an end is equivalent to
|
|
// pointer arithmetic: `ptr[start..] == ptr + start`
|
|
try expect(ptr[1..] == ptr + 1);
|
|
|
|
// subtraction between any two pointers except slices based on element size is supported
|
|
try expect(&ptr[1] - &ptr[0] == 1);
|
|
}
|
|
|
|
test "pointer arithmetic with slices" {
|
|
var array = [_]i32{ 1, 2, 3, 4 };
|
|
var length: usize = 0; // var to make it runtime-known
|
|
_ = &length; // suppress 'var is never mutated' error
|
|
var slice = array[length..array.len];
|
|
|
|
try expect(slice[0] == 1);
|
|
try expect(slice.len == 4);
|
|
|
|
slice.ptr += 1;
|
|
// now the slice is in an bad state since len has not been updated
|
|
|
|
try expect(slice[0] == 2);
|
|
try expect(slice.len == 4);
|
|
}
|
|
|
|
// test
|