When you do:
char *p= "Hello";
You are defining a string literal. String literals are constant data and as you've found out, modifying them results in undefined behavior (often a crash). It should be declared as:
const char *p = "Hello";
So the compiler will throw an error if you try to modify it.
Now if you define it instead as:
char p[] = "Hello";
The memory is then allocated on the stack and you can modify it.
int main(int argc, char *argv[])
{
char p[] = "Hello" ;
*p = 'B' ;
printf("\n%s",p);
return 0;
}
Outputs Bello
For program 2, note only q needs to be on the stack. p can remain a const pointer to a string literal, since you're only reading from it.
int main( )
{
const char *p = "Hello" ;
char q[] = "mug";
*q = *p ;
printf("\n%s",q);
return 0;
}
Outputs Hug