For starters this call
printf("%d %d %s\n", &str2, str2, str2);
invokes undefined behavior because there are used incorrect conversion formats for pointers.
A correct call can look like
printf("%p %p %s\n", ( void * )&str2, ( void * )str2, str2);
As for the output then the expression &str2
gives the address of the local variable str2
. The expression str2
gives the address of the first character of the string literal "Heyya"
that has the static storage location.
If to use the above expression with the conversion format %p
then the address will be outputted. If to use the above expression with the conversion format %s
then the string first character of which pointed to by the expression str2 will be outputted.
You should understand that the address of the variable str2 itself is different from the address of the string literal pointed to by the variable. That is the expression &str2 yields the address of the variable itself. The expression str2 yields the value stored in the variable that in turn is the address of the first character of the string literal.
As for your question
How is memory allocated in this program?
then in this declaration
char *str2 = "Heyya";
there is created a string literal "Heyya"
with the static storage duration and that has the type char[6]
(in C++ it has the type const char[6]
) and a local variable str2
with the automatic storage duration that is initialized by the address of the first character of the string literal.