authorgravatar for allanregush@hotmail.comAllan Regush <allanregush@hotmail.com> 2022-07-23 04:57:40-06:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2022-07-23 13:57:40+03:00
log9734e643fb09526fa107e5a4912fbf6d77bcb6c3
tree295b3ea6c12d4c6fafb394d19955c5cc3f02e111
parent819c868bbf362ac869ff65a9632969f3bc1a749a
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

docs: Pointer Arithmetic


1 files changed, 30 insertions(+), 0 deletions(-)

doc/langref.html.in+30
...@@ -2671,6 +2671,36 @@ test "pointer array access" {...@@ -2671,6 +2671,36 @@ test "pointer array access" {
2671 try expect(array[2] == 3);2671 try expect(array[2] == 3);
2672 ptr.* += 1;2672 ptr.* += 1;
2673 try expect(array[2] == 4);2673 try expect(array[2] == 4);
2674}
2675 {#code_end#}
2676 <p>
2677 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.
2678 </p>
2679 {#code_begin|test|pointer_arthemtic#}
2680const expect = @import("std").testing.expect;
2681
2682test "pointer arithmetic with many-item pointer" {
2683 const array = [_]i32{ 1, 2, 3, 4 };
2684 var ptr: [*]const i32 = &array;
2685
2686 try expect(ptr[0] == 1);
2687 ptr += 1;
2688 try expect(ptr[0] == 2);
2689}
2690
2691test "pointer arithmetic with slices" {
2692 var array = [_]i32{ 1, 2, 3, 4 };
2693 var length: usize = 0;
2694 var slice = array[length..array.len];
2695
2696 try expect(slice[0] == 1);
2697 try expect(slice.len == 4);
2698
2699 slice.ptr += 1;
2700 // now the slice is in an bad state since len has not been updated
2701
2702 try expect(slice[0] == 2);
2703 try expect(slice.len == 4);
2674}2704}
2675 {#code_end#}2705 {#code_end#}
2676 <p>2706 <p>