âCannotâ is a strong word, but itâs not as easy, no.
We had a nice Brainstorming thread about this a few months ago actually. In Zig, allocators do not keep track of how much memory they allocated, so you canât simply give them a pointer and call it a day, you have to tell them how much memory youâre returning.
There are some strong tradeoffs here, I prefer what Zig does (for one thing, many a pwn starts with doing mischief to the length annotations of the heap), but just asking for more memory than fits in your struct and dishing it out is complicated and hard to get right.
Yes, it is tradeoffs. I just want to make sure there really isnât an equivalent solution, because this is the first time Iâm using system level language like Zig.
I donât think the _ : [0]Level field in your version is doing anything useful, ftr.
You can replace the extra []level slice with an inline function which casts through a [*]u8 multipointer and retrieve the trailing level list that way, if you really want to go the distance.
You can replace the extra []level slice with an inline function which casts through a [*]u8 multipointer and retrieve the trailing level list that way, if you really want to go the distance.
My first solution was the one youâr advice. But self.level()[i] is so noisy.
Thereâs certainly a tradeoff between whatâs idiomatic and âcleanâ vs. doing it identically to the C code. The only necessary difference is that in Zig, the data structure has to keep track of the total allocation size somehow, in C malloc will do it.
Same amount of memory in principle, because willy nilly that amount does have to be tracked. Just a question of who is responsible for that, so to speak.
This usage is also found in the standard library, for example in keys() and values() in ArrayHashMap.
Itâs also possible to design it as self.level(i).
+1 to self.level()[i] or self.level(i). Just in case the object is copied as a whole block of memory, you donât have to deal with fixing up the level[] reference post copying.