diff options
author | Dave Gauer <dave@ratfactor.com> | 2021-05-08 18:51:08 -0400 |
---|---|---|
committer | Dave Gauer <dave@ratfactor.com> | 2021-05-08 18:51:08 -0400 |
commit | 22ac3628a15737af8f59d1e3b1d38b74edc7f1b9 (patch) | |
tree | e5939c631227cd5b873b1fd12ac2262285f07305 /exercises/078_sentinels3.zig | |
parent | 71e43b0a5048212bae960332b3451ba2ee85d4e7 (diff) | |
download | ziglings-22ac3628a15737af8f59d1e3b1d38b74edc7f1b9.tar.gz ziglings-22ac3628a15737af8f59d1e3b1d38b74edc7f1b9.tar.bz2 ziglings-22ac3628a15737af8f59d1e3b1d38b74edc7f1b9.tar.xz ziglings-22ac3628a15737af8f59d1e3b1d38b74edc7f1b9.zip |
Fix 076, add 077,078 sentinels and many-item pointers
Diffstat (limited to 'exercises/078_sentinels3.zig')
-rw-r--r-- | exercises/078_sentinels3.zig | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/exercises/078_sentinels3.zig b/exercises/078_sentinels3.zig new file mode 100644 index 0000000..bad4810 --- /dev/null +++ b/exercises/078_sentinels3.zig @@ -0,0 +1,27 @@ +// +// We were able to get a printable string out of a many-item +// pointer by using a slice to assert a specific length. +// +// But can we ever GO BACK to a sentinel-terminated pointer +// after we've "lost" the sentinel in a coercion? +// +// Yes, we can. Zig's @ptrCast() builtin can do this. Check out +// the signature: +// +// @ptrCast(comptime DestType: type, value: anytype) DestType +// +// See if you can use it to solve the same many-item pointer +// problem, but without needing a length! +// +const print = @import("std").debug.print; + +pub fn main() void { + // Again, we've coerced the sentinel-terminated string to a + // many-item pointer, which has no length or sentinel. + const data: [*]const u8 = "Weird Data!"; + + // Please cast 'data' to 'printable': + const printable: [*:0]const u8 = ???; + + print("{s}\n", .{printable}); +} |