can you tell conceptually what the problem is? If you dereference a pointer to the memory, what does this cause?
When you have a %s
slot in the format string, printf
expects to see a char*
as the corresponding argument. That's why you should pass myptr2
(which is the address of 'A'
and from which the subsequent addresses of the string characters can be deduced).
If you pass *myptr2
instead, you are basically passing the character 'A'
itself (with no information whatsoever as to where that particular 'A'
is — which would have allowed printf
to read the rest of the string). Simply put, printf
expected a pointer there, so it attempts to treat the corresponding argument as a pointer.
Now notice that the character you passed (by dereferencing a char*
, therefore getting a char
with the value of 'A'
) has a size of 1 byte, while a pointer has a size of 4 or 8 bytes typically. This means that printf
will most likely read a garbage address made up of a character and some random data found in the stack. There can be no guarantees as to what can happen to the program in this case, so the whole incident invokes undefined behavior.