mirror of
https://github.com/ziglang/zig.git
synced 2024-11-14 16:13:24 +00:00
docs: Pointer Arithmetic
This commit is contained in:
parent
819c868bbf
commit
9734e643fb
@ -2671,6 +2671,36 @@ test "pointer array access" {
|
||||
try expect(array[2] == 3);
|
||||
ptr.* += 1;
|
||||
try expect(array[2] == 4);
|
||||
}
|
||||
{#code_end#}
|
||||
<p>
|
||||
Zig supports pointer arithmetic. It's better to assign the pointer to {#syntax#}[*]T{#endsyntax#} and increment that variable. For example, directly incrementing the pointer from a slice will corrupt it.
|
||||
</p>
|
||||
{#code_begin|test|pointer_arthemtic#}
|
||||
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);
|
||||
}
|
||||
|
||||
test "pointer arithmetic with slices" {
|
||||
var array = [_]i32{ 1, 2, 3, 4 };
|
||||
var length: usize = 0;
|
||||
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);
|
||||
}
|
||||
{#code_end#}
|
||||
<p>
|
||||
|
Loading…
Reference in New Issue
Block a user