Yes, in C++ string literals have type const char[]. So you can only read them.
On the other hand the record
char s[] = "String literal";
means that a char array is created elements of which are initialized from characters of the string literal. As this array s has no const qualifier you can change it.
@vlad. ... So this is a difference b/w pointers and array?
if we define string literal as a char array. We can change it.But if declare/initialize as char pointer, we can't change its value.
I think that "String literal" is the same constant string literal regardless of the context.
But if you "give" it to a pointer, the pointer will only take its address.
While "giving" it to an array, the array copies its contents.
if we define string literal as a char array. We can change it.
No.
Anything in your code that looks like this:
"some letters"
is a string literal. It is stored in the compiled, built code looking just like that. You can open your executable with a hex editor and find it. It cannot be changed.
In your code above, the first example has a string literal. The second example does not. If you want to fiddle with string literals, you must arrange things such that you make a copy of it, and then you can fiddle with that copy.
In the first case the compiler allocates memory for string literal the same way as for array usually in a read-only memory and assigns s address of the first character of the literal.
In the second case the compiler does not allocate memory for the string literal. It allocates memory only for the array s and initialize its elements with characters from the string literal.