Thanks for the reply !
The Zig specific behaviour of comptime_int makes more sense , but for strings I can still do var input = "Hello Zig".* and then modify it to something like input[0] = 'a' and input actually changes to aello Zig. What happens in this case?
Does Zig create a copy of Hello Zig on the stack, or does it create a completely new String and then modified that ?
"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).
varstr_ptr="hi";// type: *const [2:0]u8vara=str_ptr.*;// type: [2:0]u8 varb=[2:0]u8{'y','o'};// type: same as `a`a=&b;// allowed since `b`'s type matches and `a` is var
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 !
For further actions, you may consider blocking this person and/or reporting abuse
Thanks for the reply !
The Zig specific behaviour of
comptime_int
makes more sense , but for strings I can still dovar input = "Hello Zig".*
and then modify it to something likeinput[0] = 'a'
and input actually changes toaello Zig
. What happens in this case?Does Zig create a copy of
Hello Zig
on the stack, or does it create a completely new String and then modified that ?"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).
Ok, this is the context I was missing (basically dereferring "x".*) creates a copy on the Stack that I can then modify. Thanks !