When the compiler encounters a string literal, in this case "Hello"
, memory is allocated in the static (global) memory area. This "allocation" is done before your program executes.
When your program starts executing at main
, a stack frame is allocated to store the local variables of main
: str
and i
. Note that str
is a simple variable that just stores an address. It does not store any characters. It just stores a pointer.
The statement str = &i;
writes into variable str
the address of i
.
The statement str = "Hello"
writes into the variable str
, the address of the string literal "Hello"
which has been pre-allocated by the compiler. This is a completely different address than that of i
. That assignment does not move any of the characters in the word "Hello" anywhere at all.
TL;DR the value of a "string" variable in C is just a pointer. Assigning to a string variable is assigning a number, namely an address.