054_manypointers.zig 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // You can also make pointers to multiple items without using a slice.
  3. //
  4. // var foo: [4]u8 = [4]u8{ 1, 2, 3, 4 };
  5. // var foo_slice: []u8 = foo[0..];
  6. // var foo_ptr: [*]u8 = &foo;
  7. //
  8. // The difference between foo_slice and foo_ptr is that the slice has
  9. // a known length. The pointer doesn't. It is up to YOU to keep track
  10. // of the number of u8s foo_ptr points to!
  11. //
  12. const std = @import("std");
  13. pub fn main() void {
  14. // Take a good look at the array type to which we're coercing
  15. // the zen12 string (the REAL nature of strings will be
  16. // revealed when we've learned some additional features):
  17. const zen12: *const [21]u8 = "Memory is a resource.";
  18. //
  19. // It would also have been valid to coerce to a slice:
  20. // const zen12: []const u8 = "...";
  21. //
  22. // Now let's turn this into a "many-item pointer":
  23. const zen_manyptr: [*]const u8 = zen12;
  24. // It's okay to access zen_manyptr just like an array or slice as
  25. // long as you keep track of the length yourself!
  26. //
  27. // A "string" in Zig is a pointer to an array of const u8 values
  28. // (or a slice of const u8 values, as we saw above). So, we could
  29. // treat a "many-item pointer" of const u8 as a string as long as
  30. // we can CONVERT IT TO A SLICE. (Hint: we do know the length!)
  31. //
  32. // Please fix this line so the print statement below can print it:
  33. const zen12_string: []const u8 = zen_manyptr;
  34. // Here's the moment of truth!
  35. std.debug.print("{s}\n", .{zen12_string});
  36. }
  37. //
  38. // Are all of these pointer types starting to get confusing?
  39. //
  40. // FREE ZIG POINTER CHEATSHEET! (Using u8 as the example type.)
  41. // +---------------+----------------------------------------------+
  42. // | u8 | one u8 |
  43. // | *u8 | pointer to one u8 |
  44. // | [2]u8 | two u8s |
  45. // | [*]u8 | pointer to unknown number of u8s |
  46. // | [*]const u8 | pointer to unknown number of immutable u8s |
  47. // | *[2]u8 | pointer to an array of 2 u8s |
  48. // | *const [2]u8 | pointer to an immutable array of 2 u8s |
  49. // | []u8 | slice of u8s |
  50. // | []const u8 | slice of immutable u8s |
  51. // +---------------+----------------------------------------------+