#Having problem solving ziglings 54

1 messages · Page 1 of 1 (latest)

sullen basin
#
{
    // Take a good look at the array type to which we're coercing
    // the zen12 string (the REAL nature of strings will be
    // revealed when we've learned some additional features):
    const zen12: *const [21]u8 = "Memory is a resource.";
    //
    //   It would also have been valid to coerce to a slice:
    //         const zen12: []const u8 = "...";
    //
    // Now let's turn this into a "many-item pointer":
    const zen_manyptr: [*]const u8 = zen12;

    // It's okay to access zen_manyptr just like an array or slice as
    // long as you keep track of the length yourself!
    //
    // A "string" in Zig is a pointer to an array of const u8 values
    // (or a slice of const u8 values, as we saw above). So, we could
    // treat a "many-item pointer" of const u8 as a string as long as
    // we can CONVERT IT TO A SLICE. (Hint: we do know the length!)
    //
    // Please fix this line so the print statement below can print it:
    const zen12_string: []const u8 = zen_manyptr;

    // Here's the moment of truth!
    std.debug.print("{s}\n", .{zen12_string});
}

I'm having problems solving the syntax for this problem. I've tried trying to turn zen_manyptr into a slice, or referencing or dereferencing it. I'm not sure what else I'm missing here.

crisp spoke
#

you have to slice the multipointer:

const zen12_string: []const u8 = zen_manyptr[0..21];

This tells the compiler the length of the array you're pointing to. Because of this, it can turn into a slice again.

#

both [*]const u8 and []const u8 are used as pointers to multiple items. [*]const u8 does not know it's length, []const u8 does know it length. So you have to tell the length to convert a [*]const u8 to a []const u8

sullen basin
#

Oh! I have to manually count out the length? I assumed zen_manyptr[0..] would have been enough, but it wasn't

#

Oh no, it does tell me exactly how long zen12 is

#

Perfect, thank you

amber orchid
sullen basin
#

When would you use a many items pointer?

#

Is this what you'd reach for when passing a string to another function?

amber orchid
#

But even then you wouldn't need to coerce and save it in new variable. A slice has a .ptr field that holds the underlying many items pointer.

mossy basalt
#

whoops

#

discord didnt scroll down, didnt see it was already answered

mossy basalt
# sullen basin When would you use a many items pointer?

its useful for c interop as shoebrews said, but it's also useful when you already store the length or can calculate the lenght
if you already know the length, a slice is wasting 8 bytes of memory
if you have an array of thousands of strings, youd be wasting potentially megabytes of memory to do nothing (and ofc thats bad for cache too)
its common to do stuff like storing the length in the first element or having the last element be NULL and tracking it that way instead of using a seperate length field