054_manypointers.zig 2.4 KB

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