Suppose
char* p = "alisha";
Can we change the value of string or can we make pointer point somewhere else?
In which scenarios we can and we can't change the string. Kindly explain with examples.
Suppose
char* p = "alisha";
Can we change the value of string or can we make pointer point somewhere else?
In which scenarios we can and we can't change the string. Kindly explain with examples.
String literals are stored in memory that is read-only, so you can't change it.
If you don't want the string to be changed during the program, it is better to do
char const *p = "alisha";
Then, when you try to change the string, your program will not crash with segmentation fault, it will arise a compiler error (which is much better).
Your questions can be easily answered by writing a very basic and simple program, go ahead and try it, you'll better understand things by writing code.
You can change what it points to. E.g.,
char *p="cats";
printf("%s\n",p); //prints "cats"
p="bats";
printf("%s\n",p); //prints "bats"
But, if you want to change the letters in "cats" like you would manipulate an array, then you have to use an array, like this:
char p[]="cats";
which gives you an array of characters {'c','a','t','s','\0'}, which you can manipulate like:
p[0]='b';
or whatever
You can change what string p is pointing to.
char *p;
p = "his";
printf("%s\n", p);
p = "her";
printf("%s\n", p);
will print
his
her