When you say:
char *ch = "sitaram";
The compiler does the following:
- it allocates the string "sitaram" at program start (static storage duration). This string can be put into read-only memory.
- when your program arrives at this line, it allocates the pointer
ch
, and makes this pointer to point to the statically allocated "sitaram" string.
- if you do
ch[2] = 'y'
, then you're trying to modify the 3rd character of the statically allocated string. Usually, you get a crash (because it is in read-only memory)
On the other hand, if you do the following:
char ch[] = "sitaram";
When the program hit this line, it allocates memory for the array ch[]
(for 8 chars), then copies the string "sitaram" into this memory. If you do ch[2] = 'y'
, then you modify this allocated memory, which is perfectly fine to do.
If you want to modify a string with char *
, it should point to a memory which is modifiable. For example:
char ch[] = "sitaram";
char *xx = ch;
xx[2] = 'y'; // it is the same as ch[2] = 'y';