#Slice of unknown size

1 messages · Page 1 of 1 (latest)

shadow fox
#

Hi,
I have a question about buffers.
If I declare a buffer like [10][255]u8 I will get this 10*255 buffer directly in memory (so within the declared struct).
Is there a way to do this without actually knowing the size at compile time and only at runtime like: [size][255]u8, where size is some int saved somewhere else?

I know that I could use raw array pointers or slices like [*][255]u8, however I am required to actually save the buffer and not a pointer (since I am working with shared memory on linux).

One solution I did find is that I save one [255]u8 and use it the create a slice based on its address, but that feels like a hacky solution.

Thx for answering in advance!

floral spruce
#

You can create a slice-var and reassign it later, but I can't actually understand what it is that you want, specifically. Can you give an example of your use case?

shadow fox
#

Sure. I am writing a ArrayList like thing that lives in a SHM to be shared between processes.Since SHM files are maped into the memory space using c's mmap I can sadly save no pointers within the SHM since each process might map the shared memory to another address.

#

There for I would like to save my array like

size : usize,
data : [][255]u8,

but as mentioned before data is not allowed to be a pointer.

floral spruce
#

So you're saying data lives inside a file, essentially?

#

When pointers don't work, offsets/indices do. I definitely don't really follow though, this is unfamiliar to me.

shadow fox
rancid aspen
#

I'd recommend declaring it as 0 element array so that it works with type system and retains correct alignment and element type.

Then each process would compute the appropriate slice from the size info. The zero width array also ends up marking where the first byte can be found of the variable length array

#

i did something like that before in #zig as POC for variable array member equivalent in zig

#

#zig message

shadow fox
#

@rancid aspen Thx, that seems exactly what I am trying to accomplish!

#

The zero length array is quite genuis

woven falcon
#

be sure to make it extern as normal structs do not have a gaurunteed layout.
I was going to suggest something similar, but with pointer magic.
but a trailing 0 length array is nicer, and does the same magic.
fyi, a pointer to an array can coerce to a many item pointer, no need for a cast @rancid aspen