3 ms·
// Arrays may contain a sentinel value at the end, here array.len == 4 and array[4] == 0. const array = [_:0]u8 {1, 2, 3, 4}; Small typo. Len should be 5,
by Graziano_M 4y ago
// Arrays may contain a sentinel value at the end, here array.len == 4 and array[4] == 0.
const array = [_:0]u8 {1, 2, 3, 4};
Small typo. Len should be 5, I believe.
- ptato 4y agoIt's really 4. It doesn't count the sentinel, just the elements. `@sizeOf([4:0]u8)` is 5 though.
- Graziano_M 4y agoOh, that's strange. So you can actually read (just 1) past len?
- sl3dge78 4y agoYeah, it's made to feel like strlen in a way. Sentinel types are mostly used with C code. That way strlen(some_string) == some_string.len.
- Graziano_M 4y agoAh, I hadn't thought of that analogue, but it makes sense, then. It sort of recreates the opportunity to make the common bug, though, of allocating enough for the data but not the sentinel (or enough for the string but not the null terminator).
- kristoff_it 4y agoNot really, the sentinel is part of the type and the allocator interface in Zig is type-aware, meaning that you can't simply "forget" about sentinels. The type system will fight you.
- Graziano_M 4y agoSo creating a pointer to a type with a fixed length and a sentinel and creating a new one will automatically allocate enough for the length + the sentinel? That's nice. I'm still not sure I like the .len 'misreporting' since it would be harder to manually optimize around, e.g. packing a struct with a 8 byte + sentinel array would take 16 bytes that I might not notice if I am going by `.len`. This is all speculation, though. I need to actually play around with Zig.