A buffer in the stack? How?

Example C:

char buff[100];
snprintf(buff, 100, “hello, %d”, 1 );

puts(buff);
// hello, 1

I know how to do that in odin with the string builder and fmt.sbprintf but I don’t want to use heap memory. Here is an example in Odin which is different due to using heap memory:

buff := strings.builder_make()
defer strings.builder_destroy(&buff)

fmt.sbprintf(&buf, “hello, %i”, 1)

How do you do the same as the C example which only uses stack memory but in Odin?

1 Like

You can create a strings.Builder using an existing buffer with strings.builder_from_bytes. This does not allocate.

Alternatively, fmt.bprintf can also do this for you and format directly into the given buffer. It just uses builder_from_bytes and sbprintf internally.

2 Likes

Could you give a basic example? I tried this but nothing gets printed:

buff: byte
fmt.bprintf(buff, “hello, %d”, 1)
fmt.println(buff)

1 Like

A slice is a pointer to an existing buffer (and a length), so if you just initialize a slice like that it’ll be nil. The equivalent to your original example would be:

buff : [100]u8
s := fmt.bprintf(buff[:], "hello, %d", 1)
fmt.print(s)

Also, to be clear: byte and u8 are 100% equivalent, byte is just an alias for u8. [100]byte would work too.

5 Likes