| ... | ... | @@ -2671,6 +2671,36 @@ test "pointer array access" { |
| 2671 | 2671 | try expect(array[2] == 3); |
| 2672 | 2672 | ptr.* += 1; |
| 2673 | 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#} |
| 2680 | const expect = @import("std").testing.expect; |
| 2681 | |
| 2682 | test "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 | |
| 2691 | test "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 | 2705 | {#code_end#} |
| 2676 | 2706 | <p> |