This code produces \"p = hello world\":
#include \"stdio.h\"
#include \"string.h\"
int main(){
char *p;
p=\"hello world\";
printf(\"p is %s \\n\",p)
Notice what the two working examples have in common: they have a p =
line that assigns something to p
. The non-working example does not do this.
Consider this line (from the first example):
p = "hello world";
Although it might look like it's "copying a string to a char pointer", it's not. It's copying the location of a string to a pointer-to-char. That's what a pointer-to-char like p
stores - the location of a contiguous block of char
s.
Similarly, consider this line from the third example:
p = malloc(10);
This is also copying a location - it's copying the location of a block of 10 unintialised char
s into p
.
strcpy(dest, source)
copies characters from the location given by source
to the location given by dest
. It should be clear that if you never set p
to a valid location, then strcpy(p, "hello")
can't do anything sensible - in your second example, p
is an essentially random location, and you then ask strcpy()
to copy something to that location.