I am really confused about the use of pointers on strings. It feels like they obey different rules. Consider the following code
char *ptr = "apple";// perfectly valid here not when declaring afterwards like next ptr = "apple"; // shouldn't it be *ptr = "apple"
Also
printf()
behaves differently -printf("%s", ptr) // Why should I send the address instead of the value
Also I came across the following code in a book
char str[]="Quest"; char *p="Quest"; str++; // error, constant pointer can't change *str='Z'; // works, because pointer is not constant p++; // works, because pointer is not constant *p = 'M'; // error, because string is constant
I can't understand what is supposed to imply
Please help, I can't find any info anywhere else
No, because
*ptr
would be achar
. So, you may write*ptr = 'a'
but you can't write as you suggest.Because a string in C, is the address of a sequence of characters (
char
) terminated by zero (the null character aka\x0
).No, a pointer can perfectly change, but here,
str
is an array (which is slightly different from being a pointer). But, thus, it cannot deal with pointer arithmetic.No, it works because
*str
should be achar
.No, it works because, this time, this is a pointer (not an array).
Same as above, this is a
char
again, so it works because it is the right type and not because the string is 'constant'. And, as stated by Michael Walz in the comments, even though it might compile, it will produce an undefined behavior at runtime (most likely a crash withsegfault
) because the specification do not tell if the string pointed by*p
is read-only or not (yet, it seems that most of the modern compilers implementation decide to make it in read-only). Which might produce asegfault
.For more information, refer to this SO question.