diff options
| author | Allan Regush <allanregush@hotmail.com> | 2022-07-23 04:57:40 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-07-23 13:57:40 +0300 |
| commit | 9734e643fb09526fa107e5a4912fbf6d77bcb6c3 (patch) | |
| tree | 295b3ea6c12d4c6fafb394d19955c5cc3f02e111 | |
| parent | 819c868bbf362ac869ff65a9632969f3bc1a749a (diff) | |
| download | zig-9734e643fb09526fa107e5a4912fbf6d77bcb6c3.tar.gz zig-9734e643fb09526fa107e5a4912fbf6d77bcb6c3.zip | |
docs: Pointer Arithmetic
| -rw-r--r-- | doc/langref.html.in | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/doc/langref.html.in b/doc/langref.html.in index 0da6d60257..5a46107d2a 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -2674,6 +2674,36 @@ test "pointer array access" { } {#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> In Zig, we generally prefer {#link|Slices#} rather than {#link|Sentinel-Terminated Pointers#}. You can turn an array or pointer into a slice using slice syntax. </p> |
