#How to write into a pointer to an array

1 messages · Page 1 of 1 (latest)

errant palm
#

i'm trying to pass an unknown length array buffer to a function, like this:

        const byte_buf: []u8 = allocator.alloc(u8, 4) catch |err| {
            std.log.err("failed to allocate byte buf! {s}", .{@errorName(err)});
            return ReaderError.AllocFailure;
        };
        try self.readByteArr(byte_buf, 4);

the function that takes byte_buf is of type []u8. how would i write to this byte_buf from the called function?

#

How to write into a pointer to an array

lapis blade
#

I'm not sure where the problem is.

What happened when you tried to pass to readByteArr? Was there an error?

What is the function type of readByteArr (The parameters and return type)?

errant palm
#

i'm just a bit confused. here's what readByteArr looks like:

pub fn readByteArr(self: *Self, buffer: []u8, bytes_to_read: u64) ReaderError!void {
        if (self.file_offset + bytes_to_read >= self.file_size) {
            return ReaderError.EOF;
        }

        for (0..bytes_to_read) |i| {
            buffer[i] = self.file_data[self.file_offset];
            self.file_offset += 1;
        }
}```
so i don't have to use the `ptr` field or anything, i can just index and write into `buffer` as if it was a normal array?
lyric valley
#

yeah

#

a slice is kind of like two ptrs

errant palm
#

huh alright then, good to know. thanks all!