Question with similar title is there but is different and less discriptive! I was studing use of const on string and changing string. In book follwing will work is given but does not work.
#include <stdio.h>
int main()
{
char *p="Hello";
/*same error if you add p=p-4*/
*p="bye";/*here*/
printf("%s",p);
return 0;
}
This code gives error: assigning to 'char' from incompatible type 'const char *' When i use as follows there is no error but output screen is blankblank.
/*blank output*/
#include <stdio.h>
int main()
{
char *p="Hello";
*p='p';
printf("%s",p);
return 0;
}
OR
/*blank screen*/
#include <stdio.h>
int main()
{
char *p="Hello";
p=p-3;
*p='p';
printf("%s",p);
return 0;
}
But if you use
p="bye";
It replaces string with bye.
Please see image along
String literals are read only. Unfortunately, they does not have the const char*
type. This is one difference to C++ where they actually have a const type.
Modifying a string literal is undefined behavior and you should never attempt to do that. However, this is perfectly valid:
char arr[]="Hello";
char *p = arr;
*p = 'M';
You mentioned in comments that you have learned that from the book "Let us C" which is a very bad book, that is full of errors and bad habits. I wrote a rant about that book in this answer
When i use as follows there is no error but output screen is blankblank.
That's the world of undefined behavior for you. It basically means that anything can happen since the standard puts no requirements on the compiler of what it should do when invoking undefined behavior. Please note that "working the way it is intended" is a possible outcome of undefined behavior.
p=p-3;
This line is actually also undefined behavior. Of course it's not a good thing to dereference this pointer after this operation, since it would point outside the array. So the line *p='p';
would write to unallocated memory. But actually, even performing the pointer arithmetic here is UB. If you have a pointer p
that points to an element in an array or one element past it, and an integer n
, positive or negative, then p+n
MUST result in a pointer that is still pointing to the same array or one past. Otherwise even the pointer arithmetics invokes UB.
Regarding the "one past" bit, read here: What is the rationale for one past the last element of an array object?