Zig NEWS

Discussion on: When a var really isn't a var (ft. String Literals)

Collapse
kristoff profile image
Loris Cro • Edited on

"Hello Zig" is a chunk of memory inside the .rodata of your executable (or something of that sort, I believe different architecture-specific backends can decide where this stuff goes). So when you assing it to a variable, you get a pointer to those bytes.

When you dereference the pointer you get the full array contents which, yes, get copied to stack memory (assuming we're inside a function) and that then you can modify, since that memory is yours. If you look at the types it's very clear and consistent (if you know about string interning).

var str_ptr = "hi"; // type: *const [2:0]u8
var a = str_ptr.*; // type: [2:0]u8 
var b = [2:0]u8 {'y', 'o'}; // type: same as `a`
a = &b; // allowed since `b`'s type matches and `a` is var
Enter fullscreen mode Exit fullscreen mode
Thread Thread
gowind profile image
Govind Author

When you dereference the pointer you get the full array contents which, yes, get copied to stack memory (assuming we're inside a function) and that then you can modify, since that memory is yours

Ok, this is the context I was missing (basically dereferring "x".*) creates a copy on the Stack that I can then modify. Thanks !